本文整理汇总了C#中Lidgren.Network.NetServer.ReadMessage方法的典型用法代码示例。如果您正苦于以下问题:C# NetServer.ReadMessage方法的具体用法?C# NetServer.ReadMessage怎么用?C# NetServer.ReadMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Lidgren.Network.NetServer
的用法示例。
在下文中一共展示了NetServer.ReadMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
private static void Main(string[] args)
{
var config = new NetPeerConfiguration("airgap")
{
Port = port,
MaximumConnections = 50,
ConnectionTimeout = 5f
};
config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
var server = new NetServer(config);
server.Start();
Console.WriteLine("AudioGap Server Started");
waveOut.DeviceNumber = 0; // TODO: need an option for this
while (true)
{
NetIncomingMessage msg;
if ((msg = server.ReadMessage()) == null)
{
Thread.Sleep(1);
continue;
}
switch (msg.MessageType)
{
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
Console.WriteLine(msg.ReadString());
break;
case NetIncomingMessageType.StatusChanged:
var status = (NetConnectionStatus)msg.ReadByte();
string reason = msg.ReadString();
Console.WriteLine("New status: " + status + " (" + reason + ")");
break;
case NetIncomingMessageType.ConnectionApproval:
SetupAudio(msg);
msg.SenderConnection.Approve();
break;
case NetIncomingMessageType.Data:
if (msg.SenderConnection.Status == NetConnectionStatus.Connected)
HandleAudioPacket(msg);
break;
default:
Console.WriteLine("Unhandled type: " + msg.MessageType);
break;
}
}
}
示例2: Main
static void Main(string[] args)
{
server = new NetServer(new NetPeerConfiguration("Fireworks")
{
AcceptIncomingConnections = true,
Port = 7007,
ConnectionTimeout = 5
});
server.Start();
Console.WriteLine("Started server");
while (true)
{
NetIncomingMessage message;
while ((message = server.ReadMessage()) != null)
{
switch (message.MessageType)
{
case NetIncomingMessageType.Data:
{
var type = (Protocol)message.ReadByte();
HandleIncomingData(type, message.SenderConnection, message);
break;
}
case NetIncomingMessageType.StatusChanged:
{
var status = (NetConnectionStatus) message.ReadByte();
var msg = message.ReadString();
Console.WriteLine(status);
Console.WriteLine(msg);
if (status == NetConnectionStatus.Connected)
{
Console.WriteLine("Client connected from " + message.SenderConnection.ToString());
}
else if (status == NetConnectionStatus.Disconnected)
{
Console.WriteLine("Client disconnected from " + message.SenderConnection.ToString());
}
break;
}
}
}
Thread.Sleep(1);
}
}
示例3: 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();
}
示例4: Main
static void Main(string[] args)
{
NetPeerConfiguration config = new NetPeerConfiguration("garbagethrower");
config.MaximumConnections = 1;
config.Port = 14242;
config.PingInterval = 2.0f;
config.ConnectionTimeout = 2.0f;
var server = new NetServer(config);
server.Start();
while (true)
{
NetIncomingMessage msg;
while ((msg = server.ReadMessage()) != null)
{
switch (msg.MessageType)
{
case NetIncomingMessageType.StatusChanged:
var status = (NetConnectionStatus)msg.ReadByte();
var reason = msg.ReadString();
Console.WriteLine("New status: " + status + " (" + reason + ")");
break;
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.ErrorMessage:
case NetIncomingMessageType.DebugMessage:
var str = msg.ReadString();
if (str.StartsWith("Malformed packet; stated") ||
str.StartsWith("Received unhandled library message") ||
str.StartsWith("Unexpected NetMessageType"))
break; // we'll get a bunch of these and we're fine with that
Console.WriteLine(msg.MessageType + ": " + str);
break;
case NetIncomingMessageType.Data:
Console.WriteLine("Received " + msg.LengthBits + " bits of data");
break;
case NetIncomingMessageType.UnconnectedData:
Console.WriteLine("Received " + msg.LengthBits + " bits of unconnected data");
break;
default:
Console.WriteLine("Received " + msg.MessageType);
break;
}
}
}
}
示例5: handleRequest
public void handleRequest(NetServer s)
{
NetIncomingMessage inc;
if ((inc = s.ReadMessage()) != null)
{
switch (inc.MessageType)
{
case NetIncomingMessageType.Data:
break;
default:
break;
}
}
}
示例6: Main
static void Main(string[] args)
{
NetPeerConfiguration config = new NetPeerConfiguration("LidgrenTestServer");
config.Port = 14242;
config.MaximumConnections = 200;
NetServer server = new NetServer(config);
server.Start();
NetIncomingMessage msg;
while(true)
{
if((msg = server.ReadMessage()) != null)
{
Console.WriteLine(msg.ReadString());
server.Recycle(msg);
}
Thread.Sleep(20);
}
}
示例7: Main
static void Main(string[] args)
{
var config = new NetPeerConfiguration("enctest");
config.MaximumConnections = 1;
config.Port = 14242;
var server = new NetServer(config);
server.Start();
var encryption = new NetAESEncryption(server, "Hallonpalt");
// loop forever
while (true)
{
var inc = server.ReadMessage();
if (inc != null)
{
switch (inc.MessageType)
{
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.ErrorMessage:
Console.WriteLine(inc.ReadString());
break;
case NetIncomingMessageType.StatusChanged:
var status = (NetConnectionStatus)inc.ReadByte();
Console.WriteLine(inc.SenderConnection + " (" + status + ") " + inc.ReadString());
break;
case NetIncomingMessageType.Data:
var ok = inc.Decrypt(encryption);
Console.WriteLine("Data (decrypted: " + (ok ? "ok" : "fail") + ") " + inc.ReadString());
break;
}
}
System.Threading.Thread.Sleep(1);
}
}
示例8: 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,
//.........这里部分代码省略.........
示例9: Main
static void Main(string[] args)
{
NetConfiguration config = new NetConfiguration("durable");
config.MaxConnections = 128;
config.Port = 14242;
NetServer server = new NetServer(config);
server.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true);
server.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
//server.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
server.SetMessageTypeEnabled(NetMessageType.StatusChanged, true);
server.SimulatedMinimumLatency = 0.05f;
server.SimulatedLatencyVariance = 0.025f;
server.SimulatedLoss = 0.03f;
server.Start();
FileStream fs = new FileStream("./serverlog.txt", FileMode.Create, FileAccess.Write, FileShare.Read);
StreamWriter wrt = new StreamWriter(fs);
Output(wrt, "Log started at " + DateTime.Now);
wrt.Flush();
NetBuffer buffer = server.CreateBuffer();
int expected = 1;
Console.WriteLine("Press any key to quit");
while (!Console.KeyAvailable)
{
NetMessageType type;
NetConnection sender;
if (server.ReadMessage(buffer, out type, out sender))
{
switch (type)
{
case NetMessageType.StatusChanged:
if (sender.RemoteHailData != null)
Output(wrt, "New status: " + sender.Status + " (" + buffer.ReadString() + ") Remote hail is: " + Encoding.ASCII.GetString(sender.RemoteHailData));
else
Output(wrt, "New status: " + sender.Status + " (" + buffer.ReadString() + ") Remote hail hasn't arrived.");
break;
case NetMessageType.BadMessageReceived:
case NetMessageType.ConnectionRejected:
case NetMessageType.DebugMessage:
//
// All these types of messages all contain a single string in the buffer; display it
//
Output(wrt, buffer.ReadString());
break;
case NetMessageType.VerboseDebugMessage:
wrt.WriteLine(buffer.ReadString()); // don't output to console
break;
case NetMessageType.ConnectionApproval:
if (sender.RemoteHailData != null &&
Encoding.ASCII.GetString(sender.RemoteHailData) == "Hail from client")
{
Output(wrt, "Hail ok!");
sender.Approve(Encoding.ASCII.GetBytes("Hail from server"));
}
else
{
sender.Disapprove("Wrong hail!");
}
break;
case NetMessageType.Data:
string str = buffer.ReadString();
// parse it
int nr = Int32.Parse(str.Substring(9));
if (nr != expected)
{
Output(wrt, "Warning! Expected " + expected + "; received " + nr + " str is ---" + str + "---");
}
else
{
expected++;
Console.Title = "Server; received " + nr + " messages";
}
break;
default:
Output(wrt, "Unhandled: " + type + " " + buffer.ToString());
break;
}
}
Thread.Sleep(1);
}
// clean shutdown
wrt.Close();
server.Shutdown("Application exiting");
}
示例10: Run
public void Run()
{
// Server initialization
config = new NetPeerConfiguration("stryferpg");
config.Port = 1234;
server = new NetServer(config);
server.Start();
//TODO: services initialization
// Messages receipt
bool stop = false;
NetIncomingMessage message;
while (!stop)
{
while ((message = server.ReadMessage()) != null)
{
switch (message.MessageType)
{
case NetIncomingMessageType.Data:
SRActionMessage action = NetworkSerializer.DeserializeObject<SRActionMessage>(message.ReadBytes(message.LengthBytes));
switch (action.serviceType)
{
case ServiceType.Login:
LoginService.Instance.Handle(action, message.SenderConnection);
break;
case ServiceType.Char:
break;
case ServiceType.Map:
MapService.Instance.Handle(action, message.SenderConnection);
break;
}
break;
case NetIncomingMessageType.StatusChanged:
Console.WriteLine("StatusChanged");
switch (message.SenderConnection.Status)
{
case NetConnectionStatus.Connected:
Console.WriteLine("Connected");
break;
}
break;
case NetIncomingMessageType.DebugMessage:
Console.WriteLine(message.ReadString());
break;
default:
Console.WriteLine("unhandled message with type: "
+ message.MessageType);
break;
}
}
//stop = Console.ReadKey().Key == ConsoleKey.S;
Thread.Sleep(1);
}
}
示例11: Main
static void Main()
{
var connectedPlayers = 0;
var config = new NetPeerConfiguration("romero");
config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
config.Port = 14242;
var PlayerNames = new Dictionary<long, string>();
//var xinput = 0;
//var yinput = 0;
var dummyName = string.Empty;
float angle = 0;
// create and start server
var server = new NetServer(config);
server.Start();
Console.WriteLine("Server online");
// schedule initial sending of position updates
var nextSendUpdates = NetTime.Now;
// 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)
//
var om = server.CreateMessage();
if (connectedPlayers < 4)
{
om.Write(true);
server.SendDiscoveryResponse(om, msg.SenderEndpoint);
}
else
{
om.Write(false);
server.SendDiscoveryResponse(om, 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:
var status = (NetConnectionStatus)msg.ReadByte();
if (status == NetConnectionStatus.Connected)
{
//
// A new player just connected!
//
Console.WriteLine(msg.SenderConnection.RemoteUniqueIdentifier + " connected. (IP Address: " + msg.SenderEndpoint.Address + ")");
connectedPlayers++;
Console.WriteLine(connectedPlayers + " players ingame");
};
if (status == NetConnectionStatus.Disconnected)
{
Console.WriteLine(msg.SenderConnection.RemoteUniqueIdentifier + " disconnected. (IP Address: " + msg.SenderEndpoint.Address + ")");
connectedPlayers--;
Console.WriteLine(connectedPlayers + " players ingame");
}
break;
case NetIncomingMessageType.Data:
//
// The client sent input to the server
//
dummyName = msg.ReadString();
if (!PlayerNames.ContainsKey(msg.SenderConnection.RemoteUniqueIdentifier))
{
PlayerNames.Add(msg.SenderConnection.RemoteUniqueIdentifier, dummyName);
}
// fancy movement logic goes here
var xinput = msg.ReadInt32();
var yinput = msg.ReadInt32();
//.........这里部分代码省略.........
示例12: Main
//.........这里部分代码省略.........
Console.WriteLine("Trivial tests passed in " + (timeSpan * 1000.0) + " milliseconds");
Console.WriteLine("Creating client and server for live testing...");
NetConfiguration config = new NetConfiguration("unittest");
config.Port = 14242;
NetServer server = new NetServer(config);
NetBuffer serverBuffer = new NetBuffer();
server.Start();
config = new NetConfiguration("unittest");
NetClient client = new NetClient(config);
client.SetMessageTypeEnabled(NetMessageType.Receipt, true);
NetBuffer clientBuffer = client.CreateBuffer();
client.Start();
client.Connect("127.0.0.1", 14242);
List<string> events = new List<string>();
double end = double.MaxValue;
double disconnect = double.MaxValue;
while (NetTime.Now < end)
{
double now = NetTime.Now;
NetMessageType nmt;
NetConnection sender;
//
// client
//
if (client.ReadMessage(clientBuffer, out nmt))
{
switch (nmt)
{
case NetMessageType.StatusChanged:
Console.WriteLine("Client: " + client.Status + " (" + clientBuffer.ReadString() + ")");
events.Add("CStatus " + client.Status);
if (client.Status == NetConnectionStatus.Connected)
{
// send reliable message
NetBuffer buf = client.CreateBuffer();
buf.Write(true);
buf.Write((int)52, 7);
buf.Write("Hallon");
client.SendMessage(buf, NetChannel.ReliableInOrder1, new NetBuffer("kokos"));
}
if (client.Status == NetConnectionStatus.Disconnected)
end = NetTime.Now + 1.0; // end in one second
break;
case NetMessageType.Receipt:
events.Add("CReceipt " + clientBuffer.ReadString());
break;
case NetMessageType.ConnectionRejected:
case NetMessageType.BadMessageReceived:
throw new Exception("Failed: " + nmt);
case NetMessageType.DebugMessage:
// silently ignore
break;
default:
// ignore
示例13: ProcessMessage
/// <summary>
/// ProcessMessage runs in a separate thread and manages the incoming messages of the clients.
/// </summary>
/// <param name="obj">object obj represents a NetServer object.</param>
private void ProcessMessage(object obj)
{
try
{
netServer = (NetServer)obj;
NetIncomingMessage msg;
Log.Message("Server thread started. ProcessMessage(). Current MPRole: " + MPManager.Instance.MPRole);
StopMessageProcessingThread.Condition = false;
MPManager.Instance.IsProcessMessageThreadRunning = true;
while (!StopMessageProcessingThread.Condition)
{ // As long as the netServer is started
while ((msg = netServer.ReadMessage()) != null)
{
switch (msg.MessageType)
{
// Debuggen
#region Debug
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
Log.Warning("DebugMessage: " + msg.ReadString());
break;
#endregion
// StatusChanged
#region NetIncomingMessageType.StatusChanged
case NetIncomingMessageType.StatusChanged:
NetConnectionStatus state = (NetConnectionStatus)msg.ReadByte();
if (state == NetConnectionStatus.Connected)
{
OnClientConnected(new ReceivedMessageEventArgs(msg));
}
else if (state == NetConnectionStatus.Disconnected || state == NetConnectionStatus.Disconnecting)
{
OnClientDisconnected(new ReceivedMessageEventArgs(msg));
if (netServer.ConnectionsCount == 0)
{
OnAllClientsDisconnected(new ReceivedMessageEventArgs(msg));
}
}
break;
#endregion
// If the message contains data
#region NetIncomingMessageType.Data
case NetIncomingMessageType.Data:
Log.Message("Server Incoming Message Data.");
int type = msg.ReadInt32();
Log.Message("Type: " + type + "; MPMessageType: " + (MPMessageType)type);
ProgressData((MPMessageType)type, msg); //Test
break;
#endregion
// Connectionapproval
#region NetIncomingMessageType.ConnectionApproval
case NetIncomingMessageType.ConnectionApproval:
// Connection logic. Is the user allowed to connect
// Receive information to process
string sentPassword = msg.ReadString();
string sentUsername = msg.ReadString();
int sentEnabledModCount = msg.ReadInt32();
if (netServer.ConnectionsCount <= ServerMaximumPlayerAmount)
{ // Check if server is full
Log.Warning(String.Format("User ({0}) trying to connect. Sent password: {1}", sentUsername, sentPassword));
if (ServerPassword == sentPassword)
{ // Password is the same
if (PluginManager.instance.enabledModCount == sentEnabledModCount)
{ // The client and server have the same amount of mods enabled
msg.SenderConnection.Approve();
OnClientConnectionRequestApproved(new ConnectionRequestEventArgs(msg, "User accepted", sentUsername, sentPassword));
}
else
{
msg.SenderConnection.Deny();
OnClientConenctionRequestDenied(new ConnectionRequestEventArgs(msg, String.Format("Denied: Different amount of mods activated. User: {0}; Server: {1}", sentEnabledModCount, PluginManager.instance.enabledModCount), sentUsername, sentPassword));
}
}
else
{
msg.SenderConnection.Deny();
OnClientConenctionRequestDenied(new ConnectionRequestEventArgs(msg, "Denied: Wrong password.", sentUsername, sentPassword));
}
}
else
{
msg.SenderConnection.Deny();
OnClientConenctionRequestDenied(new ConnectionRequestEventArgs(msg, "Denied: Game is full/Cannot accept any more connections.", sentUsername, sentPassword));
}
break;
#endregion
default:
OnReceivedUnhandledMessage(new ReceivedUnhandledMessageEventArgs(msg, msg.MessageType.ToString()));
//.........这里部分代码省略.........
示例14: 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");
//.........这里部分代码省略.........
示例15: Main
static void Main(string[] args)
{
Config = new NetPeerConfiguration("pokemon");
Config.Port = 7377;
Config.MaximumConnections = 20;
Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
Server = new NetServer(Config);
Server.Start();
Console.WriteLine("time to own");
/*/Creating a ContentManager to load maps from XML
Form form = new Form();
GraphicsDeviceService gds = GraphicsDeviceService.AddRef(form.Handle,
form.ClientSize.Width, form.ClientSize.Height);
ServiceContainer services = new ServiceContainer();
services.AddService<IGraphicsDeviceService>(gds);
content = new ContentManager(services, "Content");*/
//Initialize all the maps here
List<PlayerPrimitive> Players = new List<PlayerPrimitive>();
ServerNPCController = new NPCController();
NPC npc = new NPC(null, new Vector2(15, 15), 2);
ServerNPCController.addNPC(npc);
NetIncomingMessage nic;
DateTime time = DateTime.Now;
TimeSpan updateSpan = new TimeSpan(0, 0, 0, 0, 30);
Console.WriteLine("Waiting for players to join...");
while (true)
{
if ((nic = Server.ReadMessage()) != null)
{
switch (nic.MessageType)
{
case NetIncomingMessageType.ConnectionApproval :
if (nic.ReadByte() == (byte)PacketTypes.Login)
{
Console.WriteLine("New Player joining.");
nic.SenderConnection.Approve();
PlayerPrimitive prim = DataReadWrite.ReadPlayer(nic);
prim.Connection = nic.SenderConnection;
Players.Add(prim);
Console.WriteLine("The following players are in:");
foreach (PlayerPrimitive player in Players)
{
Console.WriteLine(player.Name + " joined " + System.DateTime.Now);
Console.WriteLine(player.UniqueId);
}
NetOutgoingMessage outmsg = Server.CreateMessage();
outmsg.Write((byte)PacketTypes.WorldState);
outmsg.Write(Players.Count);
foreach (PlayerPrimitive player in Players)
{
outmsg.WriteAllProperties(player);
}
Server.SendMessage(outmsg, nic.SenderConnection, NetDeliveryMethod.ReliableOrdered, 0);
Console.WriteLine("New player has joined, server updated and shit.");
}
break;
case NetIncomingMessageType.Data :
if (nic.ReadByte() == (byte)PacketTypes.Move)
{
foreach (PlayerPrimitive player in Players)
{
if (player.Connection != nic.SenderConnection)
continue;
Vector2 position = XNAExtensions.ReadVector2(nic);
bool running = nic.ReadBoolean();
player.X = (int)position.X;
player.Y = (int)position.Y;
player.IsRunning = running;
Console.WriteLine(player.Name + " position: " + player.X + ", " + player.Y + ": running = " + running);
/*NetOutgoingMessage outmsg = Server.CreateMessage();
//.........这里部分代码省略.........