本文整理汇总了C#中Lidgren.Network.NetClient.ReadMessage方法的典型用法代码示例。如果您正苦于以下问题:C# NetClient.ReadMessage方法的具体用法?C# NetClient.ReadMessage怎么用?C# NetClient.ReadMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Lidgren.Network.NetClient
的用法示例。
在下文中一共展示了NetClient.ReadMessage方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
public void Run()
{
// Client initialization
config = new NetPeerConfiguration("stryferpg");
client = new NetClient(config);
client.Start();
client.Connect("localhost", 1234);
handler = new LoginMessageHandler();
// Messages receipt
NetIncomingMessage message;
while (!stop)
{
while ((message = client.ReadMessage()) != null)
{
switch (message.MessageType)
{
case NetIncomingMessageType.Data:
SROrderMessage msg = NetworkSerializer.DeserializeObject<SROrderMessage>(message.ReadBytes(message.LengthBytes));
handler.Handle(msg);
break;
case NetIncomingMessageType.StatusChanged:
switch (message.SenderConnection.Status)
{
case NetConnectionStatus.Connected:
Console.WriteLine("Connected");
Console.WriteLine("Asking for server list...");
SRActionMessage action = new SRActionMessage(ActionType.GetServerList, ServiceType.Login);
SendMessage(action);
break;
}
break;
case NetIncomingMessageType.DebugMessage:
Console.WriteLine(message.ReadString());
break;
default:
Console.WriteLine("unhandled message with type: "
+ message.MessageType);
break;
}
}
Thread.Sleep(1);
}
}
示例2: start
public static void start()
{
net = new NetClient(config);
net.RegisterReceivedCallback(new SendOrPostCallback((e) =>
{
message = net.ReadMessage();
messageRecieved(message);
}), new SynchronizationContext());
print("info", "Starting...");
net.Start();
print("info", "Client Running");
}
示例3: Main
static void Main(string[] args)
{
var config = new NetPeerConfiguration("enctest");
var client = new NetClient(config);
client.Start();
System.Threading.Thread.Sleep(100); // give server time to start up
client.Connect("localhost", 14242);
var encryption = new NetAESEncryption(client, "Hallonpalt");
// loop forever
while (true)
{
// read messages
var inc = client.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;
}
}
// if we're connected, get input and send
if (client.ServerConnection != null && client.ServerConnection.Status == NetConnectionStatus.Connected)
{
Console.WriteLine("Type a message:");
var input = Console.ReadLine();
var msg = client.CreateMessage();
msg.Write(input);
encryption.Encrypt(msg);
var ok = client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered);
Console.WriteLine("Message sent: " + ok);
}
}
}
示例4: Main
static void Main(string[] args)
{
NetPeerConfiguration config = new NetPeerConfiguration("LidgrenTestServer");
config.AutoFlushSendQueue = false;
var s_client = new NetClient(config);
s_client.Start();
NetOutgoingMessage hail = s_client.CreateMessage("This is the hail message");
s_client.Connect("localhost", 14242, hail);
NetIncomingMessage msg;
while (true)
{
if ((msg = s_client.ReadMessage()) != null)
{
Console.WriteLine(msg.ReadString());
s_client.Recycle(msg);
}
Thread.Sleep(20);
}
}
示例5: Main
static void Main(string[] args)
{
// create a client with a default configuration
NetConfiguration config = new NetConfiguration("chatApp");
NetClient client = new NetClient(config);
client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);
client.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
//client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
client.Start();
// Wait half a second to allow server to start up if run via Visual Studio
Thread.Sleep(500);
// Emit discovery signal
client.DiscoverLocalServers(14242);
// create a buffer to read data into
NetBuffer buffer = client.CreateBuffer();
// current input string
string input = "";
// keep running until the user presses a key
Console.WriteLine("Type 'quit' to exit client");
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
s_keepGoing = true;
while (s_keepGoing)
{
NetMessageType type;
// check if any messages has been received
while (client.ReadMessage(buffer, out type))
{
switch (type)
{
case NetMessageType.ServerDiscovered:
// just connect to any server found!
// make hail
NetBuffer buf = client.CreateBuffer();
buf.Write("Hail from " + Environment.MachineName);
client.Connect(buffer.ReadIPEndPoint(), buf.ToArray());
break;
case NetMessageType.ConnectionRejected:
Console.WriteLine("Rejected: " + buffer.ReadString());
break;
case NetMessageType.DebugMessage:
case NetMessageType.VerboseDebugMessage:
Console.WriteLine(buffer.ReadString());
break;
case NetMessageType.StatusChanged:
string statusMessage = buffer.ReadString();
NetConnectionStatus newStatus = (NetConnectionStatus)buffer.ReadByte();
Console.WriteLine("New status: " + newStatus + " (" + statusMessage + ")");
break;
case NetMessageType.Data:
// The server sent this data!
string msg = buffer.ReadString();
Console.WriteLine(msg);
break;
}
}
while (Console.KeyAvailable)
{
ConsoleKeyInfo ki = Console.ReadKey();
if (ki.Key == ConsoleKey.Enter)
{
if (!string.IsNullOrEmpty(input))
{
if (input == "quit")
{
// exit application
s_keepGoing = false;
}
else
{
// Send chat message
NetBuffer sendBuffer = new NetBuffer();
sendBuffer.Write(input);
client.SendMessage(sendBuffer, NetChannel.ReliableInOrder1);
input = "";
}
}
}
else
{
input += ki.KeyChar;
}
}
Thread.Sleep(1);
}
client.Shutdown("Application exiting");
}
示例6: 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
示例7: MainWindow
public MainWindow()
{
InitializeComponent();
m_hostList = new Dictionary<long, IPEndPoint[]>();
NetPeerConfiguration config = new NetPeerConfiguration("game");
config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
m_client = new NetClient(config);
m_client.Start();
Thread thread = new Thread(delegate() {
while(true) {
NetIncomingMessage inc;
while ((inc = m_client.ReadMessage()) != null) {
switch (inc.MessageType) {
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
break;
case NetIncomingMessageType.UnconnectedData:
if (inc.SenderEndPoint.Equals(m_masterServer)) {
// it's from the master server - must be a host
var id = inc.ReadInt64();
var hostInternal = inc.ReadIPEndPoint();
var hostExternal = inc.ReadIPEndPoint();
string serverName = inc.ReadString();
string scriptName = inc.ReadString();
int players = inc.ReadInt32();
int maxPlayers = inc.ReadInt32();
m_hostList[id] = new IPEndPoint[] { hostInternal, hostExternal };
Application.Current.Dispatcher.Invoke(delegate {
ServerEntry serverEntry = null;
foreach(ServerEntry entry in spServerList.Children) {
if(Convert.ToInt64(entry.Tag) == id) {
serverEntry = entry;
}
}
if(serverEntry == null) {
serverEntry = new ServerEntry("v0.1", serverName, players, maxPlayers, -1, scriptName);
serverEntry.Tag = id;
serverEntry.UpdateView();
spServerList.Children.Add(serverEntry);
}
else {
serverEntry.ServerName = serverName;
serverEntry.Players = players;
serverEntry.Script = scriptName;
serverEntry.MaxPlayers = maxPlayers;
serverEntry.UpdateView();
}
});
}
break;
}
}
}
});
thread.IsBackground = true;
thread.Start();
}
示例8: CreateClient
/// <summary>
/// Creates a new client connection connected to the given IP end point. This method blocks
/// until we know if the client has either connected or disconnected.
/// </summary>
/// <param name="ip">The IP to connect to.</param>
/// <param name="player">This computer's player.</param>
/// <param name="password">The password that the server is expecting.</param>
/// <returns></returns>
public static Maybe<NetworkContext> CreateClient(string ip, Player player, string password) {
NetClient client = new NetClient(Configuration.GetConfiguration(server: false));
client.Start();
// Write out our hail message
{
NetOutgoingMessage hailMsg = client.CreateMessage();
HailMessageFormat hail = new HailMessageFormat() {
Player = player,
Password = password
};
string serializedHail = SerializationHelpers.Serialize(hail);
hailMsg.Write(serializedHail);
Log<NetworkContext>.Info("Trying to connect to " + ip + " on port " + Configuration.Port + " with hailing message " + serializedHail);
// Try to connect to the server
client.Connect(ip, Configuration.Port, hailMsg);
}
// Block until we know if we have connected or disconnected.
while (true) {
NetIncomingMessage msg;
while ((msg = client.ReadMessage()) != null) {
if (msg.MessageType != NetIncomingMessageType.StatusChanged) {
Log<NetworkContext>.Error("While attempting to connect to server, got unexpected message type " + msg.MessageType);
continue;
}
NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
Log<NetworkContext>.Info("While attempting to connect to server, status changed to " + status);
goto gotConnectionAttemptResult;
}
Thread.Sleep(0);
}
gotConnectionAttemptResult:
// If the connection status is not connected, then we failed, so just return an empty
// network context
if (client.ConnectionStatus != NetConnectionStatus.Connected) {
return Maybe<NetworkContext>.Empty;
}
// We're connected to the server! Read in the hail message to populate our server
// connection with the server player instance
{
NetIncomingMessage msg = client.ServerConnection.RemoteHailMessage;
Player serverPlayer = SerializationHelpers.Deserialize<Player>(msg.ReadString());
client.ServerConnection.Tag = serverPlayer;
NetworkContext context = new NetworkContext(player) {
_client = client
};
return Maybe.Just(context);
}
}
示例9: Load
public void Load()
{
isFinished = false;
// create client configuration
clientConfig = new NetPeerConfiguration("pacman");
//configure client
client = new NetClient(clientConfig);
//Start client
client.Start();
if (client != null)
{
NetIncomingMessage msg;
bool waitingForServer = true;
// Contact Server
client.DiscoverKnownPeer("localhost", 666);
//client.DiscoverLocalPeers(666);
while (waitingForServer)
{
while ((msg = client.ReadMessage()) != null)
{
switch (msg.MessageType)
{
case NetIncomingMessageType.DiscoveryResponse:
try
{
client.Connect(msg.SenderEndpoint);
//waitingForServer = false;
}
catch (Exception e)
{
System.Console.WriteLine(e.ToString());
//waitingForServer = false;
}
break;
case NetIncomingMessageType.Data:
if (msg.ReadString() == "connected")
{
waitingForServer = false;
}
break;
}
}
if (timeoutCount > timeoutLimit)
{
waitingForServer = false;
}
double elapsedTime = gameTime.ElapsedGameTime.TotalMilliseconds;
timeoutCount += elapsedTime;
}
}
foreach (GameScreen screen in gameScreens)
{
if (screen is ConfigMultiplayerScreen)
{
//((ConfigMultiplayerScreen)screen).setClient(client);
//((ConfigMultiplayerScreen)screen).setConntectedServer(client.ServerConnection.RemoteEndpoint.Address.ToString());
}
screenManager.AddScreen(screen, PlayerIndex.One);
}
isFinished = true;
}
示例10: Main
static void Main(string[] args)
{
NetConfiguration config = new NetConfiguration("durable");
NetClient client = new NetClient(config);
client.SimulatedMinimumLatency = 0.05f;
client.SimulatedLatencyVariance = 0.025f;
client.SimulatedLoss = 0.03f;
// wait half a second to allow server to start up in Visual Studio
Thread.Sleep(500);
// create a buffer to read data into
NetBuffer buffer = client.CreateBuffer();
// connect to localhost
client.Connect("localhost", 14242, Encoding.ASCII.GetBytes("Hail from client"));
// enable some library messages
client.SetMessageTypeEnabled(NetMessageType.BadMessageReceived, true);
//client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);
FileStream fs = new FileStream("./clientlog.txt", FileMode.Create, FileAccess.Write, FileShare.Read);
StreamWriter wrt = new StreamWriter(fs);
Output(wrt, "Log started at " + DateTime.Now);
wrt.Flush();
// create a stopwatch
Stopwatch sw = new Stopwatch();
sw.Start();
int loops = 0;
while (!Console.KeyAvailable)
{
NetMessageType type;
if (client.ReadMessage(buffer, out type))
{
switch (type)
{
case NetMessageType.StatusChanged:
if (client.ServerConnection.RemoteHailData != null)
Output(wrt, "New status: " + client.Status + " (" + buffer.ReadString() + ") Remote hail is: " + Encoding.ASCII.GetString(client.ServerConnection.RemoteHailData));
else
Output(wrt, "New status: " + client.Status + " (" + buffer.ReadString() + ") Remote hail hasn't arrived.");
break;
case NetMessageType.BadMessageReceived:
case NetMessageType.ConnectionRejected:
case NetMessageType.DebugMessage:
case NetMessageType.VerboseDebugMessage:
//
// These types of messages all contain a string in the buffer; display it.
//
Output(wrt, buffer.ReadString());
break;
case NetMessageType.Data:
default:
//
// For this application; server doesn't send any data... so Data messages are unhandled
//
Output(wrt, "Unhandled: " + type + " " + buffer.ToString());
break;
}
}
// send a message every second
if (client.Status == NetConnectionStatus.Connected && sw.Elapsed.TotalMilliseconds >= 516)
{
loops++;
//Console.WriteLine("Sending message #" + loops);
Console.Title = "Client; Messages sent: " + loops;
Output(wrt, "Sending #" + loops + " at " + NetTime.ToMillis(NetTime.Now));
NetBuffer send = client.CreateBuffer();
send.Write("Message #" + loops);
client.SendMessage(send, NetChannel.ReliableInOrder14);
sw.Reset();
sw.Start();
}
Thread.Sleep(1);
}
// clean shutdown
client.Shutdown("Application exiting");
wrt.Close();
}
示例11: MessageLoop
/// <summary>
/// Main message loop.
/// Reads data from the server and stores and received message.
/// </summary>
private void MessageLoop()
{
NetPeerConfiguration cfg = new NetPeerConfiguration("Asteria");
cfg.MaximumConnections = 1;
cfg.ReceiveBufferSize = 1024;
cfg.MaximumTransmissionUnit = 4095;
client = new NetClient(cfg);
client.Start();
messages = new Dictionary<MessageType, List<BaseServerMessage>>();
NetIncomingMessage receivedMsg;
while (isRunning)
{
lock (client)
receivedMsg = client.ReadMessage();
if (receivedMsg != null)
{
switch (receivedMsg.MessageType)
{
case NetIncomingMessageType.ConnectionApproval:
#if DEBUG
Console.WriteLine("Approval: " + receivedMsg.ReadString());
#endif
break;
case NetIncomingMessageType.StatusChanged:
NetConnectionStatus status = (NetConnectionStatus)receivedMsg.ReadByte();
#if DEBUG
Console.WriteLine("Status changed: " + status.ToString());
#endif
if (status == NetConnectionStatus.Connected)
{
isConnected = true;
OnConnected();
}
else if (status == NetConnectionStatus.Disconnected)
{
isConnected = false;
OnDisconnected();
}
break;
case NetIncomingMessageType.Data:
byte[] byteBuffer = new byte[receivedMsg.LengthBytes];
receivedMsg.ReadBytes(byteBuffer, 0, receivedMsg.LengthBytes);
BaseServerMessage msg = deserializer.Deserialize(byteBuffer);
if (msg != null)
{
lock (messages)
{
if (!messages.ContainsKey(msg.MessageType))
messages.Add(msg.MessageType, new List<BaseServerMessage>());
messages[msg.MessageType].Add(msg);
}
OnMessageReceived(msg.MessageType, msg);
}
break;
}
}
else
client.MessageReceivedEvent.WaitOne(500);
}
}
示例12: DispatchIM
/// <summary>
///
/// </summary>
/// <param name="message"></param>
void DispatchIM ( NetClient client )
{
NetIncomingMessage msg;
while ((msg = client.ReadMessage()) != null)
{
switch (msg.MessageType)
{
case NetIncomingMessageType.VerboseDebugMessage:Log.Debug ("UI Net: " + msg.ReadString()); break;
case NetIncomingMessageType.DebugMessage: Log.Verbose ("UI Net: " + msg.ReadString()); break;
case NetIncomingMessageType.WarningMessage: Log.Warning ("UI Net: " + msg.ReadString()); break;
case NetIncomingMessageType.ErrorMessage: Log.Error ("UI Net: " + msg.ReadString()); break;
case NetIncomingMessageType.DiscoveryResponse:
DiscoveryResponse( msg.SenderEndPoint, msg.ReadString() );
break;
//case NetIncomingMessageType.StatusChanged:
// var status = (NetConnectionStatus)msg.ReadByte();
// var message = msg.ReadString();
// Log.Message("UI: {0} - {1}", status, message );
// break;
//case NetIncomingMessageType.Data:
// var netCmd = (NetCommand)msg.ReadByte();
// state.DataReceived( netCmd, msg );
// break;
default:
Log.Warning("CL: Unhandled type: " + msg.MessageType);
break;
}
client.Recycle(msg);
}
}
示例13: DispatchIM
/// <summary>
///
/// </summary>
/// <param name="message"></param>
void DispatchIM ( NetClient client )
{
NetIncomingMessage msg;
while ((msg = client.ReadMessage()) != null)
{
switch (msg.MessageType)
{
case NetIncomingMessageType.VerboseDebugMessage:Log.Debug ("CL Net: " + msg.ReadString()); break;
case NetIncomingMessageType.DebugMessage: Log.Verbose ("CL Net: " + msg.ReadString()); break;
case NetIncomingMessageType.WarningMessage: Log.Warning ("CL Net: " + msg.ReadString()); break;
case NetIncomingMessageType.ErrorMessage: Log.Error ("CL Net: " + msg.ReadString()); break;
case NetIncomingMessageType.ConnectionLatencyUpdated:
ping = msg.ReadFloat();
if (Game.Network.ShowLatency) {
Log.Verbose("...CL ping - {0} {1,6:0.00} ms", msg.SenderEndPoint, (ping*1000) );
}
break;
case NetIncomingMessageType.StatusChanged:
var status = (NetConnectionStatus)msg.ReadByte();
var message = msg.ReadString();
Log.Message("CL: {0} - {1}", status, message );
state.StatusChanged( status, message, msg.SenderConnection );
break;
case NetIncomingMessageType.Data:
var netCmd = (NetCommand)msg.ReadByte();
state.DataReceived( netCmd, msg );
break;
default:
Log.Warning("CL: Unhandled type: " + msg.MessageType);
break;
}
client.Recycle(msg);
}
}