本文整理汇总了C#中Lidgren.Network.NetServer.SendMessage方法的典型用法代码示例。如果您正苦于以下问题:C# NetServer.SendMessage方法的具体用法?C# NetServer.SendMessage怎么用?C# NetServer.SendMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Lidgren.Network.NetServer
的用法示例。
在下文中一共展示了NetServer.SendMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Process
public static void Process(NetServer server, NetBuffer buffer, NetConnection sender)
{
Config config = Config.Instance;
List<NetConnection> connections = server.Connections;
//Lets send that message onto any plugin clients
foreach (NetConnection connection in connections)
{
if (config.Server.client_connections.ContainsKey(connection.RemoteEndpoint.ToString()))
{
string client_type = (string)config.Server.client_connections[connection.RemoteEndpoint.ToString()];
if (client_type.ToLower() == "plugin")
{
string msg = buffer.ReadString();
Console.WriteLine("Slave: Data sent - " + msg);
NetBuffer slavebuf = server.CreateBuffer();
slavebuf.Write(msg);
server.SendMessage(slavebuf, connection, NetChannel.ReliableInOrder4);
}
}
}
}
示例2: 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;
}
}
示例3: 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);
}
示例4: 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);
}
}
示例5: 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);
}
}
示例6: LoginMessageImpl
private void LoginMessageImpl(NetServer server, NetIncomingMessage im, MessageBase msg)
{
var registerMsg = msg as LoginMessage;
var r = new LoginResultMessage();
var user = AdventurePluginDB.User.Get(registerMsg.Name, registerMsg.Pass);
if (user != null)
{
r.Result = "OK";
r.UserId = user.id;
}
else
{
r.Result = "Error";
}
server.SendMessage(r, im.SenderConnection);
}
示例7: RegisterMessageImpl
private void RegisterMessageImpl(NetServer server, NetIncomingMessage im, MessageBase msg)
{
var registerMsg = msg as RegisterMessage;
var r = new RegisterResultMessage();
if (AdventurePluginDB.User.Get(registerMsg.Name, registerMsg.Pass) == null)
{
var user = new UserInfo
{
Name = registerMsg.Name,
Pass = registerMsg.Pass,
};
AdventurePluginDB.User.Create(user);
r.Result = "OK";
}
else
{
r.Result = "Error";
}
server.SendMessage(r, im.SenderConnection);
}
示例8: 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.");
}
}
示例9: 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");
//.........这里部分代码省略.........
示例10: 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,
//.........这里部分代码省略.........
示例11: 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.");
//.........这里部分代码省略.........
示例12: 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)
//.........这里部分代码省略.........
示例13: Main
//.........这里部分代码省略.........
NetOutgoingMessage returnMessage = server.CreateMessage();
NetworkPlayer newPlayer = new NetworkPlayer(physicsWorld, msg.SenderConnection, new Vector2(0,0));
//ShapeTeam team = (ShapeTeam)msg.ReadByte();
string username = msg.ReadString();
try
{
//newPlayer.SetTeam(team);
newPlayer.SetUserName(username);
int spot = AddNewPlayer(newPlayer);
newPlayer.indexOnServer = spot;
//Assign the new player to the team with the least amount of players
ShapeTeamContainer newPlayerTeam = greenTeam.GetNumberOfMembers() < redTeam.GetNumberOfMembers() ? greenTeam : redTeam;
bool isBank = newPlayerTeam.AddPlayer(newPlayer.indexOnServer);
newPlayer.SetTeam(newPlayerTeam.GetTeam());
newPlayer.body.Position = ConvertUnits.ToSimUnits(newPlayerTeam.basePosition);
if (isBank)
newPlayer.SetClass(new ShapeClassBank());
else
newPlayer.SetClass(new ShapeClassKnocker());
newPlayer.OnCreateRemnant += CreateRemnant;
}
catch(Exception e)
{
returnMessage.Write((byte)ShapeCustomNetMessageType.SetupFailed);
returnMessage.Write(e.Message);
server.SendMessage(returnMessage, newPlayer.netConnection, NetDeliveryMethod.ReliableUnordered);
break;
}
returnMessage.Write((byte)ShapeCustomNetMessageType.SetupSuccessful);
returnMessage.Write(newPlayer.indexOnServer);
returnMessage.Write((byte)newPlayer.team);
returnMessage.Write(connectedPlayersActual);
for (int i = 0; i < connectedPlayers.Length; i++)
{
if(connectedPlayers[i] != null)
{
returnMessage.Write(connectedPlayers[i].indexOnServer);
returnMessage.Write((byte)connectedPlayers[i].team);
returnMessage.Write(connectedPlayers[i].power);
}
}
server.SendMessage(returnMessage, newPlayer.netConnection, NetDeliveryMethod.ReliableUnordered);
if(connectedPlayersActual > 1)
{
NetOutgoingMessage newPlayerMessage = server.CreateMessage();
newPlayerMessage.Write((byte)ShapeCustomNetMessageType.NewPlayerJoined);
newPlayerMessage.Write(newPlayer.indexOnServer);
newPlayerMessage.Write((byte)newPlayer.team);
newPlayerMessage.Write(/*newPlayer.power*/5);
server.SendMessage(newPlayerMessage, GetRecipients(newPlayer.indexOnServer), NetDeliveryMethod.ReliableUnordered, 0);
}
示例14: Start
public static void Start()
{
NetPeerConfiguration config = new NetPeerConfiguration("xnaapp");
config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
config.Port = 14242;
// create and start server
NetServer server = new NetServer(config);
server.Start();
// schedule initial sending of position updates
double nextSendUpdates = NetTime.Now;
// run until escape is pressed
//while (!Console.KeyAvailable || Console.ReadKey().Key != ConsoleKey.Escape)
while(true)
{
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!");
// randomize his position and store in connection tag
msg.SenderConnection.Tag = new int[] {
NetRandom.Instance.Next(10, 100),
NetRandom.Instance.Next(10, 100)
};
}
break;
case NetIncomingMessageType.Data:
//
// The client sent input to the server
//
int xinput = msg.ReadInt32();
int yinput = msg.ReadInt32();
int[] pos = msg.SenderConnection.Tag as int[];
// fancy movement logic goes here; we just append input to position
pos[0] += xinput;
pos[1] += yinput;
break;
}
//
// send position updates 30 times per second
//
double now = NetTime.Now;
if (now > nextSendUpdates)
{
// Yes, it's time to send position updates
// for each player...
foreach (NetConnection player in server.Connections)
{
// ... send information about every other player (actually including self)
foreach (NetConnection otherPlayer in server.Connections)
{
// send position update about 'otherPlayer' to 'player'
NetOutgoingMessage om = server.CreateMessage();
// write who this position is for
om.Write(otherPlayer.RemoteUniqueIdentifier);
if (otherPlayer.Tag == null)
otherPlayer.Tag = new int[2];
int[] pos = otherPlayer.Tag as int[];
om.Write(pos[0]);
om.Write(pos[1]);
// send message
server.SendMessage(om, player, NetDeliveryMethod.Unreliable);
}
}
//.........这里部分代码省略.........
示例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();
//.........这里部分代码省略.........