本文整理汇总了C#中Lidgren.Network.NetServer.SendDiscoveryResponse方法的典型用法代码示例。如果您正苦于以下问题:C# NetServer.SendDiscoveryResponse方法的具体用法?C# NetServer.SendDiscoveryResponse怎么用?C# NetServer.SendDiscoveryResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Lidgren.Network.NetServer
的用法示例。
在下文中一共展示了NetServer.SendDiscoveryResponse方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: MGServer_DoWork
//.........这里部分代码省略.........
NetIncomingMessage msg;
while ((msg = peer.ReadMessage ()) != null) {
switch (msg.MessageType) {
case NetIncomingMessageType.UnconnectedData :
break;
case NetIncomingMessageType.NatIntroductionSuccess:
#if !WINDOWS_PHONE
Game.Instance.Log("NAT punch through OK " + msg.SenderEndpoint);
#endif
peer.Connect (msg.SenderEndpoint);
break;
case NetIncomingMessageType.DiscoveryRequest:
//
// Server received a discovery request from a client; send a discovery response (with no extra data attached)
//
// Get the primary local gamer
LocalNetworkGamer localMe = session.LocalGamers [0];
NetOutgoingMessage om = peer.CreateMessage ();
om.Write (session.RemoteGamers.Count);
om.Write (localMe.Gamertag);
om.Write (session.PrivateGamerSlots);
om.Write (session.MaxGamers);
om.Write (localMe.IsHost);
int[] propertyData = new int[session.SessionProperties.Count * 2];
NetworkSessionProperties.WriteProperties (session.SessionProperties, propertyData);
for (int x = 0; x < propertyData.Length; x++) {
om.Write (propertyData [x]);
}
peer.SendDiscoveryResponse (om, msg.SenderEndpoint);
break;
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
//
// Just print diagnostic messages to console
//
#if !WINDOWS_PHONE
Game.Instance.Log(msg.ReadString());
#endif
break;
case NetIncomingMessageType.StatusChanged:
NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte ();
if (status == NetConnectionStatus.Disconnected) {
#if !WINDOWS_PHONE
Game.Instance.Log(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " disconnected! from " + msg.SenderEndpoint);
#endif
CommandGamerLeft cgj = new CommandGamerLeft (msg.SenderConnection.RemoteUniqueIdentifier);
CommandEvent cmde = new CommandEvent (cgj);
session.commandQueue.Enqueue (cmde);
}
if (status == NetConnectionStatus.Connected) {
//
// A new player just connected!
//
if (!pendingGamers.ContainsKey (msg.SenderConnection.RemoteUniqueIdentifier)) {
#if !WINDOWS_PHONE
Game.Instance.Log(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected! from " + msg.SenderEndpoint);
#endif
pendingGamers.Add (msg.SenderConnection.RemoteUniqueIdentifier, msg.SenderConnection);
SendProfileRequest (msg.SenderConnection);
示例3: 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();
//.........这里部分代码省略.........
示例4: Run
public static void Run()
{
// initialize
int mapDimension = 16;
Map mapServer = Map.GenerateShipsOnMap(new Map(mapDimension));
Map mapHuman = Map.GenerateShipsOnMap(new Map(mapDimension));
Player playerServer = new Player("Server", mapServer); // non-player-character ie our server
Player playerHuman = new Player("Human", mapHuman); // player character
int currentRound = 0;
ArrayList sequences = initSequenceList("Scripts");
NetPeerConfiguration config = new NetPeerConfiguration("xnaapp");
config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
config.Port = 14242;
// create and start server
NetServer server = new NetServer(config);
try
{
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!");
// create new player object
// initialize new game
//playerServer.startGame();
//playerHuman.startGame();
}
break;
case NetIncomingMessageType.Data:
String responseString = "Nothing happend";
// player round
// The client sent input to the server
String sequenceName = msg.ReadString();
int round = msg.ReadInt32();
if (round > currentRound)
{
currentRound = round;
if (sequences.Contains(sequenceName))
{
// choose and fire sequence
var executer = new SequenceExecuter(playerServer.map);
var resultMessagePlayer = executer.LoadScript(sequenceName);
// switch round to npc
// fire random sequence
int randomIndex = RandomNumber(0, sequences.Count);
sequenceName = (String)sequences[randomIndex];
executer = new SequenceExecuter(playerHuman.map);
var resultMessageNPC = executer.LoadScript(sequenceName);
// send response to client
String battlefield = Battlefield.Draw(playerHuman, playerServer);
//.........这里部分代码省略.........
示例5: Main
//.........这里部分代码省略.........
}
foreach (KeyValuePair<long, Client> entry in UserToConnection)
{
//if (entry.Key != inc.SenderConnection.RemoteUniqueIdentifier)
{
NetOutgoingMessage syncClient = server.CreateMessage();
syncClient.Write((byte) PacketTypes.RECEIVEPLAYER);
syncClient.Write(entry.Value.Name);
syncClient.Write(entry.Key);
var buffer1 = entry.Value.Buffer;
syncClient.Write(buffer1.Length);
syncClient.Write(buffer1);
Console.WriteLine(buffer1.Length);
Console.WriteLine("SENT Client Name: {0}| Client ID: {1}", entry.Value.Name,
entry.Key);
Console.WriteLine("TO: {0}", inc.SenderConnection);
server.SendMessage(syncClient, inc.SenderConnection,
NetDeliveryMethod.ReliableOrdered); //CLIENT
}
}
break;
case PacketTypes.SENDPOS:
UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Score =
Convert.ToInt16(inc.ReadString());
Console.WriteLine("{0}'s score is now: {1}",
UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Name,
UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Score);
ID = inc.SenderConnection.RemoteUniqueIdentifier;
UpdateScore();
break;
case PacketTypes.STARTGAME:
//GOGOGOGO
Console.WriteLine("START THE GAME");
Started = true;
foreach (KeyValuePair<long, Client> entry in UserToConnection)
{
{
NetOutgoingMessage syncClient = server.CreateMessage();
syncClient.Write((byte) PacketTypes.STARTGAME);
syncClient.Write("Go");
syncClient.Write(
UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Score);
server.SendMessage(syncClient, entry.Value.Connection,
NetDeliveryMethod.ReliableOrdered);
}
}
break;
case PacketTypes.CHATSEND:
string messager = inc.ReadString();
Console.WriteLine("{0} : {1}",
UserToConnection[inc.SenderConnection.RemoteUniqueIdentifier].Name,
messager);
RelayChat(inc.SenderConnection.RemoteUniqueIdentifier, messager);
break;
}
break;
case NetIncomingMessageType.StatusChanged:
Console.WriteLine(inc.SenderConnection + " status changed. " + inc.SenderConnection.Status);
if (inc.SenderConnection.Status == NetConnectionStatus.Disconnected ||
inc.SenderConnection.Status == NetConnectionStatus.Disconnecting)
{
UserToConnection.Remove(inc.SenderConnection.RemoteUniqueIdentifier);
NetOutgoingMessage outmsg = server.CreateMessage();
outmsg.WriteVariableInt64(inc.SenderConnection.RemoteUniqueIdentifier);
server.SendToAll(outmsg, NetDeliveryMethod.ReliableOrdered);
}
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("WOW ~NETWORKING~");
server.SendDiscoveryResponse(discovermsg, inc.SenderEndPoint);
break;
}
}
Thread.Sleep(1);
}
}
示例6: 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)
//.........这里部分代码省略.........
示例7: 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);
}
}
//.........这里部分代码省略.........
示例8: DispatchIM
/// <summary>
///
/// </summary>
/// <param name="message"></param>
void DispatchIM ( GameTime gameTime, SnapshotQueue queue, NetServer server )
{
NetIncomingMessage msg;
while ((msg = server.ReadMessage()) != null)
{
switch (msg.MessageType)
{
case NetIncomingMessageType.VerboseDebugMessage:Log.Debug ("SV Net: " + msg.ReadString()); break;
case NetIncomingMessageType.DebugMessage: Log.Verbose ("SV Net: " + msg.ReadString()); break;
case NetIncomingMessageType.WarningMessage: Log.Warning ("SV Net: " + msg.ReadString()); break;
case NetIncomingMessageType.ErrorMessage: Log.Error ("SV Net: " + msg.ReadString()); break;
case NetIncomingMessageType.ConnectionLatencyUpdated:
if (Game.Network.ShowLatency) {
float latency = msg.ReadFloat();
Log.Verbose("...SV ping - {0} {1,6:0.00} ms", msg.SenderEndPoint, (latency*1000) );
}
break;
case NetIncomingMessageType.DiscoveryRequest:
Log.Message("Discovery request from {0}", msg.SenderEndPoint.ToString() );
var response = server.CreateMessage( ServerInfo() );
server.SendDiscoveryResponse( response, msg.SenderEndPoint );
break;
case NetIncomingMessageType.ConnectionApproval:
var userGuid = msg.SenderConnection.GetHailGuid();
var userInfo = msg.SenderConnection.GetHailUserInfo();
var reason = "";
var approve = ApproveClient( userGuid, userInfo, out reason );
if (approve) {
msg.SenderConnection.Approve( server.CreateMessage( ServerInfo() ) );
} else {
msg.SenderConnection.Deny( reason );
}
break;
case NetIncomingMessageType.StatusChanged:
DispatchStatusChange( msg );
break;
case NetIncomingMessageType.Data:
DispatchDataIM( gameTime, queue, msg );
break;
default:
Log.Warning("SV: Unhandled type: " + msg.MessageType);
break;
}
server.Recycle(msg);
}
}
示例9: Main
static void Main(string[] args)
{
NetPeerConfiguration config = new NetPeerConfiguration("projectorigin");
config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
config.Port = 14242;
// Create and start server
NetServer server = new NetServer(config);
server.Start();
Console.WriteLine("Game Server starts");
//Schedule initial sending of position updates
double nextSendUpdates = NetTime.Now;
GameStatus gameStatus = GameStatus.Initial;
int clientDoneCounter = 0;
//Generate a map and wait client to connect
//InternalMap map = GenerateMap();
int mapSeed = 1000;
Random rand = new Random();
mapSeed = rand.Next();
//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)
//
NetOutgoingMessage com = server.CreateMessage();
//byte[] mapData = Serializer<InternalMap>.SerializeObject(map);
switch (server.ConnectionsCount)
{
case 0:
com.Write((int)PlayerId.Green);
com.Write((int)mapSeed); //Write map seed
break;
case 1:
com.Write((int)PlayerId.Red);
com.Write((int)mapSeed); //Write map seed
gameStatus = GameStatus.Receive;
break;
}
server.SendDiscoveryResponse(com, msg.SenderEndpoint);
Console.WriteLine("Connect to: " + msg.SenderEndpoint);
break;
case NetIncomingMessageType.Data:
if (gameStatus == GameStatus.Receive)
{
//
// The client sent input to the server
//
IncomingMessageType imt = (IncomingMessageType)msg.ReadByte();
if (imt == IncomingMessageType.DataPlayerInfo)
{
int wayPointCounter = msg.ReadInt32();
List<PlayerInfo> wayPoints = new List<PlayerInfo>();
for (int i = 1; i <= wayPointCounter; ++i)
{
Vector3 tempPos;
tempPos.X = msg.ReadFloat();
tempPos.Y = msg.ReadFloat();
tempPos.Z = msg.ReadFloat();
float tempOrientation;
tempOrientation = msg.ReadFloat();
PlayerInfo wayPoint = new PlayerInfo(tempPos, tempOrientation);
wayPoints.Add(wayPoint);
}
playerInfoDict[msg.SenderEndpoint] = wayPoints;
Console.WriteLine("Receive message from" + msg.SenderEndpoint);
clientDoneCounter++;
if (clientDoneCounter == 2)
gameStatus = GameStatus.Sending;
}
}
break;
}
//
// send position updates 30 times per second
//
if (gameStatus == GameStatus.Sending)
{
// Yes, it's time to send position updates
// for each player...
foreach (NetConnection player in server.Connections)
{
if (!playerInfoDict.ContainsKey(player.RemoteEndpoint))
playerInfoDict[player.RemoteEndpoint] = new List<PlayerInfo>();
//.........这里部分代码省略.........
示例10: Main
public static void Main()
{
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;
Dictionary<NetConnection, List<Damage>> damages = new Dictionary<NetConnection, List<Damage>>();
Dictionary<NetConnection, Position> positions = new Dictionary<NetConnection, Position>();
List<Npc> npcs = new List<Npc>();
npcs.Add(new Npc { X = 1700, Y = 1000, Speed = 4, Life = 3 });
// run until escape is pressed
int i = 0;
while (IsRunning)
{
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());
Debug.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!");
Debug.WriteLine(NetUtility.ToHexString(msg.SenderConnection.RemoteUniqueIdentifier) + " connected!");
msg.SenderConnection.Tag = new object[6];
}
break;
case NetIncomingMessageType.Data:
//
// The client sent input to the server
//
MessageRouts messageRout = (MessageRouts)msg.ReadByte();
switch (messageRout)
{
case MessageRouts.Position:
Position position = new Position();
position.X = msg.ReadInt32();
position.Y = msg.ReadInt32();
position.Angle = msg.ReadInt32();
position.IsShooting = msg.ReadBoolean();
position.IsHuman = msg.ReadBoolean();
positions[msg.SenderConnection] = position;
break;
case MessageRouts.Fire:
Damage damage = new Damage();
damage.PlayerId = msg.ReadInt64();
damage.WeaponId = msg.ReadByte();
damage.Angle = msg.ReadByte();
damage.X = msg.ReadInt32();
damage.Y = msg.ReadInt32();
if (damage.PlayerId > 50)
{
if (!damages.ContainsKey(msg.SenderConnection))
damages[msg.SenderConnection] = new List<Damage>();
damages[msg.SenderConnection].Add(damage);
}
else
{
npcs[(int)damage.PlayerId].Life -= 1;
if (npcs[(int)damage.PlayerId].Life <= 0)
npcs.RemoveAt((int)damage.PlayerId);
}
break;
}
break;
//.........这里部分代码省略.........