本文整理汇总了C#中Lidgren.Network.NetServer.CreateMessage方法的典型用法代码示例。如果您正苦于以下问题:C# NetServer.CreateMessage方法的具体用法?C# NetServer.CreateMessage怎么用?C# NetServer.CreateMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Lidgren.Network.NetServer
的用法示例。
在下文中一共展示了NetServer.CreateMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: HandleMessage
private static void HandleMessage(NetIncomingMessage inc, NetServer server)
{
switch (inc.MessageType)
{
case NetIncomingMessageType.ConnectionApproval: //If ConnectionApproval request
if (inc.ReadByte() == (byte) PacketTypes.Headers.Login)
{
string username = inc.ReadString();
Console.WriteLine("New Login Request from: {0}", username);
if (username.Length > 1 & Players.Values.All(c => c.Name != username) &
!_badwordList.Contains(username, StringComparer.OrdinalIgnoreCase))
{
inc.SenderConnection.Approve();
NetOutgoingMessage connectedMessage = server.CreateMessage();
Thread.Sleep(500);
Console.WriteLine("Sending a ack to {0}", username);
connectedMessage.Write((byte) PacketTypes.Headers.LoggedIn);
connectedMessage.Write(true);
server.SendMessage(connectedMessage, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
}
else
{
inc.SenderConnection.Deny("Bad Username");
}
}
break;
case NetIncomingMessageType.Data:
byte packetheader = inc.ReadByte();
HandleProtocol(inc, packetheader, server);
break;
case NetIncomingMessageType.StatusChanged:
Console.WriteLine(inc.SenderConnection + " status changed. " + inc.SenderConnection.Status);
if (inc.SenderConnection.Status == NetConnectionStatus.Disconnected)
{
Console.WriteLine("Player: {0} has disconnected",
Players[inc.SenderConnection.RemoteUniqueIdentifier].Name);
Players.Remove(inc.SenderConnection.RemoteUniqueIdentifier);
}
break;
case NetIncomingMessageType.DiscoveryRequest:
NetOutgoingMessage discovermsg = server.CreateMessage();
discovermsg.Write("Hey I just met you, I'm a server, so address me maybe");
Console.WriteLine(@"Auto Discovery Request");
server.SendDiscoveryResponse(discovermsg, inc.SenderEndPoint);
break;
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.ErrorMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.VerboseDebugMessage:
Console.WriteLine(@"---Debug---");
Console.WriteLine(inc.ReadString());
Console.WriteLine(@"---End---");
break;
}
}
示例2: SendMessage
private static void SendMessage(NetServer server, MsgBase msg, NetConnection conn)
{
NetOutgoingMessage om = server.CreateMessage();
om.Write(msg.Id);
msg.W(om);
server.SendMessage(om, conn, NetDeliveryMethod.Unreliable, 0);
}
示例3: Initialize
private void Initialize()
{
mConfig.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
mConfig.Port = port;
mPeer = new NetServer(mConfig);
mPeer.Start();
mOutgoingMessage = mPeer.CreateMessage();
while(true) CheckForMessages();
}
示例4: UpdateResource
public void UpdateResource(NetServer server, Player ply)
{
try
{
NetOutgoingMessage msg = server.CreateMessage();
msg.Write("GAMERES");
msg.Write(ply.Resources.ToString());
ply.Connection.SendMessage(msg, NetDeliveryMethod.ReliableOrdered);
}
catch (Exception) { }
}
示例5: DispatchPacket
private static void DispatchPacket(NetServer server, int id, NetIncomingMessage msg)
{
List<NetConnection> all = server.Connections;
all.Remove(msg.SenderConnection);
if (all.Count > 0)
{
NetOutgoingMessage om = server.CreateMessage();
om.Write(id);
om.Write(msg);
server.SendMessage(om, all, NetDeliveryMethod.Unreliable, 0);
}
}
示例6: Main
static void Main(string[] args)
{
IPEndPoint masterServerEndpoint = NetUtility.Resolve("localhost", CommonConstants.MasterServerPort);
NetPeerConfiguration config = new NetPeerConfiguration("game");
config.SetMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess, true);
config.Port = 14242;
NetServer server = new NetServer(config);
server.Start();
Console.WriteLine("Server started; waiting 5 seconds...");
System.Threading.Thread.Sleep(5000);
var lastRegistered = -60.0f;
while(Console.KeyAvailable == false || Console.ReadKey().Key != ConsoleKey.Escape)
{
// (re-)register periodically with master server
if (NetTime.Now > lastRegistered + 60)
{
// register with master server
NetOutgoingMessage regMsg = server.CreateMessage();
regMsg.Write((byte)MasterServerMessageType.RegisterHost);
IPAddress mask;
IPAddress adr = NetUtility.GetMyAddress(out mask);
regMsg.Write(server.UniqueIdentifier);
regMsg.Write(new IPEndPoint(adr, 14242));
Console.WriteLine("Sending registration to master server");
server.SendUnconnectedMessage(regMsg, masterServerEndpoint);
lastRegistered = (float)NetTime.Now;
}
NetIncomingMessage inc;
while ((inc = server.ReadMessage()) != null)
{
switch (inc.MessageType)
{
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
Console.WriteLine(inc.ReadString());
break;
}
}
System.Threading.Thread.Sleep(1);
}
Console.ReadKey();
}
示例7: Server
private List<BaseUnit> UnitsList; // array of all units on the map
#endregion Fields
#region Constructors
// 1 0 0 0 0
public Server()
{
config = new NetPeerConfiguration("StarKampf") { Port = 12345 };
server = new NetServer(config);
server.Start();
outMsg = server.CreateMessage();
StrCommand = new List<string>();
UnitsList = new List<BaseUnit>();
int[] arr;
arr = System.IO.File.ReadAllText("Units/unicorn.txt").Split(' ').Select(n => int.Parse(n)).ToArray();
//ini timer
sw = new Stopwatch();
}
示例8: SendMessageExceptOne
public static void SendMessageExceptOne(NetServer server, IMessage msg, NetConnection except)
{
NetOutgoingMessage om = server.CreateMessage();
om.Write(msg.Id);
msg.Write(om);
List<NetConnection> all = server.Connections;
if (all.Contains(except))
{
all.Remove(except);
}
if (all.Count > 0)
{
server.SendMessage(om, all, NetDeliveryMethod.Unreliable, 0);
}
}
示例9: ConnectionApproval
private static void ConnectionApproval(NetIncomingMessage inc, NetServer server)
{
Console.WriteLine("======== CONNECTION APPROVAL METHOD ========");
Console.WriteLine("\nNew Connection Incoming...");
var data = inc.ReadByte();
if (data == (byte)PacketType.Login)
{
var outMsg = server.CreateMessage();
outMsg.Write((byte)PacketType.Login);
outMsg.Write(true);
Console.WriteLine(inc.SenderConnection);
Console.WriteLine("Server sending reply...");
server.SendMessage(outMsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
//Console.WriteLine(inc.SenderConnection.Status);
//Console.WriteLine("Connected: " + server.ConnectionsCount);
Console.WriteLine("======== CONNECTION APPROVAL METHOD ======== \n");
}
else
{
inc.SenderConnection.Deny("Didn't send correct information.");
}
}
示例10: Main
public static void Main(string[] args)
{
Console.WriteLine("[SERVER] Testing Lidgren-Network-v3...");
NetPeerConfiguration serverConfig = new NetPeerConfiguration("test");
serverConfig.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
serverConfig.MaximumConnections = 32;
serverConfig.Port = 12345;
NetServer server = new NetServer(serverConfig);
server.Start();
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
server.RegisterReceivedCallback(new SendOrPostCallback(GotMessage));
while(true) {
string msg = Console.ReadLine();
NetOutgoingMessage sendMsg = server.CreateMessage();
sendMsg.Write("[SERVER] " + msg);
server.SendToAll(sendMsg, NetDeliveryMethod.ReliableOrdered);
}
}
示例11: Main
static void Main(string[] args)
{
IPEndPoint masterServerEndpoint = NetUtility.Resolve("localhost", CommonConstants.MasterServerPort);
NetPeerConfiguration config = new NetPeerConfiguration("game");
config.SetMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess, true);
config.Port = 14242;
NetServer server = new NetServer(config);
server.Start();
Console.WriteLine("Server started; waiting 5 seconds...");
System.Threading.Thread.Sleep(5000);
var lastRegistered = -60.0f;
while(Console.KeyAvailable == false || Console.ReadKey().Key != ConsoleKey.Escape)
{
// (re-)register periodically with master server
if (NetTime.Now > lastRegistered + 60)
{
// register with master server
NetOutgoingMessage regMsg = server.CreateMessage();
regMsg.Write((byte)MasterServerMessageType.RegisterHost);
IPAddress mask;
IPAddress adr = NetUtility.GetMyAddress(out mask);
regMsg.Write(server.UniqueIdentifier);
regMsg.Write(new IPEndPoint(adr, 14242));
Console.WriteLine("Sending registration to master server");
server.SendUnconnectedMessage(regMsg, masterServerEndpoint);
lastRegistered = (float)NetTime.Now;
}
NetIncomingMessage inc;
while ((inc = server.ReadMessage()) != null)
{
switch (inc.MessageType)
{
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
Console.WriteLine(inc.ReadString());
break;
case NetIncomingMessageType.Data:
// incoming chat message from a client
string chat = inc.ReadString();
Console.WriteLine(chat);
//Output("Broadcasting '" + chat + "'");
// broadcast this to all connections, except sender
List<NetConnection> all = server.Connections; // get copy
all.Remove(inc.SenderConnection);
if (all.Count > 0) {
NetOutgoingMessage om = server.CreateMessage();
om.Write(NetUtility.ToHexString(inc.SenderConnection.RemoteUniqueIdentifier) + " said: " + chat);
server.SendMessage(om, all, NetDeliveryMethod.ReliableOrdered, 0);
}
break;
}
}
System.Threading.Thread.Sleep(1);
}
Console.ReadKey();
}
示例12: Main
static void Main(string[] args)
{
// Create new instance of configs. Parameter is "application Id". It has to be same on client and server.
Config = new NetPeerConfiguration("game");
// Set server port
Config.Port = 14242;
// Max client amount
Config.MaximumConnections = 200;
// Enable New messagetype. Explained later
Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
// Create new server based on the configs just defined
Server = new NetServer(Config);
// Start it
Server.Start();
// Eh..
Console.WriteLine("Server Started");
// Create list of "Characters" ( defined later in code ). This list holds the world state. Character positions
List<Character> GameWorldState = new List<Character>();
// Object that can be used to store and read messages
NetIncomingMessage inc;
// Check time
DateTime time = DateTime.Now;
// Create timespan of 30ms
TimeSpan timetopass = new TimeSpan(0, 0, 0, 0, 30);
// Write to con..
Console.WriteLine("Waiting for new connections and updateing world state to current ones");
// Main loop
// This kind of loop can't be made in XNA. In there, its basically same, but without while
// Or maybe it could be while(new messages)
while (true)
{
// Server.ReadMessage() Returns new messages, that have not yet been read.
// If "inc" is null -> ReadMessage returned null -> Its null, so dont do this :)
if ((inc = Server.ReadMessage()) != null)
{
// Theres few different types of messages. To simplify this process, i left only 2 of em here
switch (inc.MessageType)
{
// If incoming message is Request for connection approval
// This is the very first packet/message that is sent from client
// Here you can do new player initialisation stuff
case NetIncomingMessageType.ConnectionApproval:
// Read the first byte of the packet
// ( Enums can be casted to bytes, so it be used to make bytes human readable )
if (inc.ReadByte() == (byte)PacketTypes.LOGIN)
{
Console.WriteLine("Incoming LOGIN");
// Approve clients connection ( Its sort of agreenment. "You can be my client and i will host you" )
inc.SenderConnection.Approve();
// Init random
Random r = new Random();
// Add new character to the game.
// It adds new player to the list and stores name, ( that was sent from the client )
// Random x, y and stores client IP+Port
GameWorldState.Add(new Character(inc.ReadString(), r.Next(1, 40), r.Next(1, 20),inc.SenderConnection));
// Create message, that can be written and sent
NetOutgoingMessage outmsg = Server.CreateMessage();
// first we write byte
outmsg.Write((byte)PacketTypes.WORLDSTATE);
// then int
outmsg.Write(GameWorldState.Count);
// iterate trought every character ingame
foreach (Character ch in GameWorldState)
{
// This is handy method
// It writes all the properties of object to the packet
outmsg.WriteAllProperties(ch);
}
// Now, packet contains:
// Byte = packet type
// Int = how many players there is in game
// character object * how many players is in game
// Send message/packet to all connections, in reliably order, channel 0
// Reliably means, that each packet arrives in same order they were sent. Its slower than unreliable, but easyest to understand
Server.SendMessage(outmsg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered, 0);
// Debug
Console.WriteLine("Approved new connection and updated the world status");
//.........这里部分代码省略.........
示例13: Main
static void Main(string[] args)
{
//Setup the policy server first.
const string AllPolicy =
@"<?xml version='1.0'?>
<cross-domain-policy>
<allow-access-from domain=""*"" to-ports=""*"" />
</cross-domain-policy>";
SocketPolicyServer policyServer = new SocketPolicyServer(AllPolicy);
int ret = policyServer.Start();
if (ret != 0)
Console.WriteLine("Failed to start policy server.");
else
Console.WriteLine("Policy service started.");
//Alright, now onto the regular server.
config = new NetPeerConfiguration("crab_battle");
config.Port = 14248;
config.MaximumConnections = 10;
config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
server = new NetServer(config);
server.Start();
Console.WriteLine("Crab Battle server open for business.");
NetIncomingMessage inc;
DateTime time = DateTime.Now;
DateTime lastBeat = DateTime.Now;
DateTime introtime = DateTime.Now;
TimeSpan timetopass = new TimeSpan(0,0,0,0,50);
TimeSpan beatrate = new TimeSpan(0, 0, 1);
TimeSpan introlength;
bool skipintro = false;
if(skipintro == true)
introlength = new TimeSpan(0, 0, 3);
else
introlength = new TimeSpan(0, 0, 21);
int beatnum = 0;
players = new List<PlayerObject>();
int playercount = 0;
NetOutgoingMessage outmsg;
int gamePhase = 0;
int gameDifficulty = 1;
healthMod = 1;
CrabBehavior crab = new CrabBehavior();
while(true)
{
//The gamestate stuff comes first because we drop a continue if no packet is recieved.
if (gamePhase != (int)GameState.Lobby && players.Count == 0)
{
Console.WriteLine("All players disconnected, returning to lobby gamestate.");
gamePhase = (int)GameState.Lobby;
}
if (gamePhase == (int)GameState.Intro && ((introtime + introlength) < DateTime.Now))
{
//Intro has ran for it's length, lets start the game proper.
outmsg = server.CreateMessage();
outmsg.Write((byte)PacketTypes.StartGame);
server.SendMessage(outmsg, server.Connections, NetDeliveryMethod.ReliableOrdered, 1);
crab.Direction = false;
gamePhase = (int)GameState.InGame;
}
if(gamePhase == (int)GameState.InGame)
{
crab.GoGoBattleCrab();
}
//Handle dropping players.
if ((time + timetopass) < DateTime.Now)
{
for (int i = 0; i < players.Count; i++)
{
PlayerObject player = players[i];
//Make sure everyone is connected, and if not drop them.
if (player.Connection.Status == NetConnectionStatus.Disconnected || player.Connection.Status == NetConnectionStatus.Disconnecting)
{
Console.WriteLine(player.Name + " has disconnected, removing player object.");
//.........这里部分代码省略.........
示例14: Main
private static void Main(string[] args)
{
//TODO: Chat
//TODO: UPnP
//TODO: Fix Simulated Conditions
config = new NetPeerConfiguration("spacebargame") {Port = 666, EnableUPnP = true, MaximumConnections = 50};
config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
server = new NetServer(config);
server.Start();
server.UPnP.ForwardPort(666, "Spacebar Game 2013");
NetIncomingMessage inc; // Incoming Message
//Write to con..
var consoleInput = new Thread(ConsoleIn); //Console.ReadLine is blocked, Thread it
consoleInput.Start(); //Start the Thread
UserToConnection = new Dictionary<long, Client>(); //UserStore
while (true) //While True
{
if ((inc = server.ReadMessage()) != null) //if message is not null
{
//Console.WriteLine(inc.MessageType); //Print MessageType
switch (inc.MessageType)
{
case NetIncomingMessageType.ConnectionApproval: //If ConnectionApproval request
if (inc.ReadByte() == (byte) PacketTypes.LOGIN) //and LOGIN PacketHeader
{
Console.WriteLine("Incoming LOGIN"); //Incoming Login
Name = inc.ReadString(); //Name is String Sent by Client
Console.WriteLine(Name); //Print Name
if (server.ConnectionsCount == 0) //ConnectionCount = 0
{
Started = false; //Reset
}
if (UserToConnection.Values.Any(c => c.Name == Name) || Started || Name.Length >= 12)
//If Name exists, or Game has Started or the Length is more then 12
{
inc.SenderConnection.Deny("Duplicate Name"); //Deny
}
else
{
inc.SenderConnection.Approve(); //Else Allow
UserToConnection.Add(inc.SenderConnection.RemoteUniqueIdentifier,
new Client(Name, inc.SenderConnection, 0, new byte[00000000]));
//Add them to the Dictionary for PlayerStore
}
Thread.Sleep(500); //Sleep for Half a Second
if (server.ConnectionsCount == 1) //If Server.ConnectionCount is 1 they are host
{
NetOutgoingMessage msg = server.CreateMessage(); //Host Message
msg.Write((byte) PacketTypes.HOST); //Write HOST PacketHeader
msg.Write("Congratulations, You are the host");
server.SendMessage(msg, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
}
}
break;
case NetIncomingMessageType.Data:
var packetheader = inc.ReadByte();
switch ((PacketTypes) packetheader)
{
case PacketTypes.AVATAR:
var bufferLength = inc.ReadInt32();
var buffer = inc.ReadBytes(bufferLength);
Console.WriteLine("Buffer Length:" + bufferLength);
UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Buffer = buffer;
foreach (KeyValuePair<long, Client> entry in UserToConnection)
{
if (entry.Key != inc.SenderConnection.RemoteUniqueIdentifier)
{
NetOutgoingMessage syncClient = server.CreateMessage();
syncClient.Write((byte) PacketTypes.RECEIVEPLAYER);
syncClient.Write(Name);
syncClient.Write(inc.SenderConnection.RemoteUniqueIdentifier);
var buffer1 =
UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Buffer;
syncClient.Write(buffer1.Length);
syncClient.Write(buffer1);
Console.WriteLine("SENT Client Name: {0}| Client ID: {1}", Name,
inc.SenderConnection.RemoteUniqueIdentifier);
Console.WriteLine("TO: {0}, {1}", entry.Value.Name, entry.Value.Score);
server.SendMessage(syncClient, entry.Value.Connection,
//.........这里部分代码省略.........
示例15: Main
static void Main(string[] args)
{
sem = new Semaphore(1, 1);
NetPeerConfiguration config = new NetPeerConfiguration("robotcontra");
config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
config.Port = 16868;
Thread _writeClientUpdate = new Thread(new ThreadStart(writeClientsUpdate));
// create and start server
server = new NetServer(config);
server.Start();
gameOver = false;
finishWritingLevel = false;
// schedule initial sending of position updates
double nextSendUpdates = NetTime.Now;
_writeClientUpdate.Start();
// run until escape is pressed
while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
{
NetIncomingMessage msg;
while ((msg = server.ReadMessage()) != null)
{
switch (msg.MessageType)
{
case NetIncomingMessageType.DiscoveryRequest:
//
// Server received a discovery request from a client; send a discovery response (with no extra data attached)
//
server.SendDiscoveryResponse(null, msg.SenderEndPoint);
break;
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
//
// Just print diagnostic messages to console
//
Console.WriteLine(msg.ReadString());
break;
case NetIncomingMessageType.StatusChanged:
NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
if (status == NetConnectionStatus.Connected)
{
//
// A new player just connected!
//
Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected!");
multiplayerPlayers.Add(new MultiplayerPlayers(msg.SenderConnection.RemoteUniqueIdentifier));
// randomize his position and store in connection tag
if (multiplayerPlayers.Count <= 1)
{
multiplayerPlayers[0].x = 10;
multiplayerPlayers[0].y = 350;
multiplayerPlayers[0].initialX = multiplayerPlayers[0].x;
multiplayerPlayers[0].initialY = multiplayerPlayers[0].y;
}
else
{
multiplayerPlayers[multiplayerPlayers.Count-1].x = multiplayerPlayers[multiplayerPlayers.Count - 2].x + 70;
multiplayerPlayers[multiplayerPlayers.Count-1].y = multiplayerPlayers[multiplayerPlayers.Count - 2].y;
multiplayerPlayers[multiplayerPlayers.Count - 1].initialX = multiplayerPlayers[multiplayerPlayers.Count - 1].x;
multiplayerPlayers[multiplayerPlayers.Count - 1].initialY = multiplayerPlayers[multiplayerPlayers.Count - 1].y;
}
for (int i = 0; i < server.Connections.Count; i++)
{
if (server.Connections[i].RemoteUniqueIdentifier == msg.SenderConnection.RemoteUniqueIdentifier)
{
NetConnection player = server.Connections[i] as NetConnection;
NetOutgoingMessage outMessage = server.CreateMessage();
outMessage.Write((byte)PacketTypes.CREATEPLAYER);
outMessage.Write((long)multiplayerPlayers[i].id);
outMessage.Write((float)multiplayerPlayers[i].x);
outMessage.Write((float)multiplayerPlayers[i].y);
server.SendMessage(outMessage, player, NetDeliveryMethod.ReliableOrdered);
break;
}
}
SetEnemyTarget();
}
else if (status == NetConnectionStatus.Disconnected || status == NetConnectionStatus.Disconnecting)
{
Console.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " DISCONNECTED FROM SERVER!");
for (int i = 0; i < multiplayerPlayers.Count; i++)
{
if (multiplayerPlayers[i].id == msg.SenderConnection.RemoteUniqueIdentifier)
{
if (multiplayerPlayers[i].isHost)
//.........这里部分代码省略.........