internal static int SendDisconnected(NetBase netBase, string reason, NetConnection connection) { NetMessage bye = new NetMessage(NetMessageType.Handshake, reason.Length + 3); bye.Write((byte)NetHandshakeType.Disconnected); bye.Write(reason); return(netBase.SendSingleMessageAtOnce(bye, connection, connection.RemoteEndpoint)); }
internal void SendOptimizeInfo(float roundtrip) { NetMessage ping = new NetMessage(NetMessageType.PingPong, 3); ping.Write(false); // meaningless ping.Write(true); // means optimize info ping.Write7BitEncodedUInt((uint)(roundtrip * 1000.0f)); m_connection.SendMessage(ping, NetChannel.Unreliable); }
/// <summary> /// Reuses the string table index /// </summary> public int Rewrite(NetMessage msg, int idx, string str) { while (m_data.Count < idx - 1) m_data.Add(null); // dummy values m_data[idx] = str; msg.Write(false); msg.Write7BitEncodedUInt((uint)idx); msg.Write(str); return idx; }
internal static void ReplyPong(NetMessage pingMessage, NetConnection connection) { byte nr = pingMessage.ReadByte(6); NetMessage pong = new NetMessage(NetMessageType.PingPong, 3); pong.Write(true); // means pong pong.Write(false); // means NOT optimize info pong.Write(nr, 6); pong.WriteSendStamp(); connection.Parent.SendSingleMessageAtOnce(pong, connection, connection.RemoteEndpoint); }
internal static int SendConnectResponse(NetBase netBase, NetConnection clientConnection, IPEndPoint remoteEndpoint) { double now = NetTime.Now; ushort nowEnc = NetTime.Encoded(now); NetMessage response = new NetMessage(NetMessageType.Handshake, 3); response.Write((byte)NetHandshakeType.ConnectResponse); response.Write(nowEnc); clientConnection.m_firstSentHandshake = now; clientConnection.m_lastSentHandshake = now; return(netBase.SendSingleMessageAtOnce(response, clientConnection, remoteEndpoint)); }
/// <summary> /// Reuses the string table index /// </summary> public int Rewrite(NetMessage msg, int idx, string str) { while (m_data.Count < idx - 1) { m_data.Add(null); // dummy values } m_data[idx] = str; msg.Write(false); msg.Write7BitEncodedUInt((uint)idx); msg.Write(str); return(idx); }
public static NetMessage EncodeResponse(NetServer server) { if (server == null) { throw new ArgumentNullException("server"); } NetMessage msg = new NetMessage(server.Configuration.ServerName.Length + 4); msg.m_type = NetMessageType.Discovery; msg.Write((ushort)server.NumConnected); msg.Write((ushort)server.Configuration.MaximumConnections); msg.Write((string)server.Configuration.ServerName); return(msg); }
internal void SendPing(double now) { m_pingNrInProgress++; if (m_pingNrInProgress > 63) { m_pingNrInProgress = 0; } NetMessage ping = new NetMessage(NetMessageType.PingPong, 1); ping.Write(false); // means ping ping.Write(false); // means NOT optimize info ping.Write((byte)m_pingNrInProgress, 6); m_connection.Parent.SendSingleMessageAtOnce(ping, m_connection, m_connection.RemoteEndpoint); m_lastSentPing = now; }
/// <summary> /// Returns encoded index /// </summary> public int Write(NetMessage msg, string str) { int idx = m_data.IndexOf(str); if (idx == -1) { idx = m_data.Count; m_data.Add(str); msg.Write(false); msg.Write7BitEncodedUInt((uint)idx); msg.Write(str); return idx; } msg.Write(true); msg.Write7BitEncodedUInt((uint)idx); return idx; }
/// <summary> /// Returns encoded index /// </summary> public int Write(NetMessage msg, string str) { int idx = m_data.IndexOf(str); if (idx == -1) { idx = m_data.Count; m_data.Add(str); msg.Write(false); msg.Write7BitEncodedUInt((uint)idx); msg.Write(str); return(idx); } msg.Write(true); msg.Write7BitEncodedUInt((uint)idx); return(idx); }
internal static int SendConnect(NetClient client, IPEndPoint remoteEndpoint, byte[] customData) { if (client.Configuration.UsesEncryption) { client.Log.Debug("Sending Connect containing key: " + Convert.ToBase64String(client.ServerConnection.m_encryption.SymmetricEncryptionKeyBytes)); } else { client.Log.Debug("Sending Connect - Unencrypted connection!"); } NetMessage msg = new NetMessage(NetMessageType.Handshake, 3); msg.Write((byte)NetHandshakeType.Connect); msg.WriteSendStamp(); // encrypt symmetric key using server public key if (client.Configuration.UsesEncryption) { byte[] encryptedKey = client.ServerConnection.m_encryption.EncryptRSA(client.ServerConnection.m_encryption.SymmetricEncryptionKeyBytes); msg.Write((ushort)encryptedKey.Length); msg.Write(encryptedKey); } else { // request no encryption msg.Write((ushort)0); } if (customData == null || customData.Length < 1) { msg.Write7BitEncodedUInt(0); } else { msg.Write7BitEncodedUInt((uint)customData.Length); msg.Write(customData); } return(client.SendSingleMessageAtOnce(msg, null, remoteEndpoint)); }
// Serialization / Deserialization public NetMessage GetNetMessage() { MemoryStream s = new MemoryStream(); BinaryFormatter b = new BinaryFormatter(); b.Serialize(s, this); // WAY TOO BIG !! NetMessage netmsg = new NetMessage(); s.Capacity = (int)s.Length; netmsg.Write(s.GetBuffer()); return netmsg; }
public static NetMessage EncodeRequest(NetClient client) { if (client == null) { throw new ArgumentNullException("client"); } NetMessage msg = new NetMessage(); msg.m_type = NetMessageType.Discovery; msg.Write(client.Configuration.ApplicationIdentifier); return(msg); }
private bool Send(String msg) { NetMessage outMsg = new NetMessage(); outMsg.Write(msg); return m_client.SendMessage(outMsg, NetChannel.Unreliable); }
internal override void HandlePacket(NetBuffer buffer, int bytesReceived, IPEndPoint sender) { double now = NetTime.Now; try { NetMessage msg; if (m_serverConnection == null || m_serverConnection.Status == NetConnectionStatus.Disconnected) { // // unconnected packet // msg = NetMessage.Decode(buffer); if (msg == null) { Log.Warning("Malformed NetMessage?"); return; // malformed? } Log.Verbose("Received unconnected message: " + msg); // discovery response? if (msg.m_type == NetMessageType.Discovery) { NetServerInfo info = NetDiscovery.DecodeResponse(msg, sender); if (ServerDiscovered != null) ServerDiscovered(this, new NetServerDiscoveredEventArgs(info)); return; } if (m_serverConnection != null && sender.Equals(m_serverConnection.RemoteEndpoint)) { // we have m_serverConnection, but status is disconnected Log.Warning("Received " + buffer.LengthBytes + " from server; but we're disconnected!"); return; } Log.Warning("Received " + buffer.LengthBytes + " bytes from non-server source: " + sender + "(server is " + m_serverConnection.RemoteEndpoint + ")"); return; } // decrypt in place if (m_serverConnection.m_encryption.SymmetricEncryptionKeyBytes != null) { byte[] savedBuffer = null; if (m_serverConnection.Status == NetConnectionStatus.Connecting) { // special case; save buffer in case we get unencrypted response savedBuffer = new byte[buffer.LengthBytes]; Array.Copy(buffer.Data, 0, savedBuffer, 0, buffer.LengthBytes); } bool ok = m_serverConnection.m_encryption.DecryptSymmetric(buffer); if (!ok) { // failed to decrypt; drop this packet UNLESS we're in a connecting state, // in which case the server may want to tell us something if (m_serverConnection.Status == NetConnectionStatus.Connecting) { // ok let this one thru unencrypted Array.Copy(savedBuffer, buffer.Data, savedBuffer.Length); } else { Log.Warning("Failed to decrypt packet from server!"); return; } } } m_serverConnection.m_lastHeardFromRemote = now; int messagesReceived = 0; int usrMessagesReceived = 0; int ackMessagesReceived = 0; while (buffer.ReadBitsLeft > 7) { msg = NetMessage.Decode(buffer); if (msg == null) break; // done messagesReceived++; msg.Sender = m_serverConnection; switch (msg.m_type) { case NetMessageType.Handshake: NetHandshakeType tp = (NetHandshakeType)msg.ReadByte(); if (tp == NetHandshakeType.Connect || tp == NetHandshakeType.ConnectionEstablished) { Log.Warning("Client received " + tp + "?!"); } else if (tp == NetHandshakeType.ConnectResponse) { if (m_serverConnection.Status != NetConnectionStatus.Connecting) { Log.Verbose("Received redundant ConnectResponse!"); break; } // Log.Debug("ConnectResponse received"); m_serverConnection.SetStatus(NetConnectionStatus.Connected, "Connected"); Log.Info("Connected to " + m_serverConnection.RemoteEndpoint); // initialize ping to now - m_firstSentConnect float initRoundtrip = (float)(now - m_serverConnection.m_firstSentHandshake); m_serverConnection.m_ping.Initialize(initRoundtrip); ushort remoteValue = msg.ReadUInt16(); m_serverConnection.RemoteClockOffset = NetTime.CalculateOffset(now, remoteValue, initRoundtrip); Log.Verbose("Initializing remote clock offset to " + m_serverConnection.RemoteClockOffset + " ms (roundtrip " + NetUtil.SecToMil(initRoundtrip) + " ms)"); NetMessage established = new NetMessage(NetMessageType.Handshake, 3); established.Write((byte)NetHandshakeType.ConnectionEstablished); established.WriteSendStamp(); SendSingleMessageAtOnce(established, m_serverConnection, m_serverConnection.RemoteEndpoint); } else { // Disconnected string reason = msg.ReadString(); m_serverConnection.SetStatus(NetConnectionStatus.Disconnected, reason); } break; case NetMessageType.Acknowledge: //Log.Debug("Received ack " + msg.SequenceChannel + "|" + msg.SequenceNumber); m_serverConnection.ReceiveAcknowledge(msg); ackMessagesReceived++; break; case NetMessageType.PingPong: bool isPong = msg.ReadBoolean(); bool isOptimizeInfo = msg.ReadBoolean(); if (isOptimizeInfo) { m_serverConnection.m_ping.HandleOptimizeInfo(now, msg); } else if (isPong) { if (m_serverConnection.Status == NetConnectionStatus.Connected) m_serverConnection.m_ping.HandlePong(now, msg); } else { NetPing.ReplyPong(msg, m_serverConnection); } break; case NetMessageType.User: case NetMessageType.UserFragmented: //Log.Debug("User message received; " + msg.m_buffer.LengthBytes + " bytes"); m_serverConnection.ReceiveMessage(now, msg); usrMessagesReceived++; break; case NetMessageType.Discovery: NetServerInfo info = NetDiscovery.DecodeResponse(msg, sender); if (ServerDiscovered != null) ServerDiscovered(this, new NetServerDiscoveredEventArgs(info)); break; default: Log.Warning("Client received " + msg.m_type + "?!"); break; } } // add statistics NetStatistics stats = m_serverConnection.Statistics; stats.PacketsReceived++; stats.MessagesReceived += messagesReceived; stats.UserMessagesReceived += usrMessagesReceived; stats.AckMessagesReceived += ackMessagesReceived; stats.BytesReceived += bytesReceived; } catch (Exception ex) { Log.Error("Failed to parse packet correctly; read/write mismatch? " + ex); } }
void OnStatusChange(object sender, NetStatusEventArgs e) { m_log.Info(e.Connection + ": " + e.Connection.Status + " - " + e.Reason); if (e.Connection.Status == NetConnectionStatus.Connected) { NetMessage outMsg = new NetMessage(); outMsg.Write("MSG:Server:Welcome:0.01:" + m_players.Count); Server.SendMessage(outMsg, e.Connection, NetChannel.Unreliable); NetPlayer ins = new NetPlayer(e.Connection, ""); m_players.Add(ins); Console.WriteLine("Client connected; " + Server.NumConnected + " of 100"); } if (e.Connection.Status == NetConnectionStatus.Disconnected) { //HaveDeconnection = true; //RemoveDeconnectedPlayer(); for (int i = 0; i < m_players.Count; i++) { NetPlayer tmp = m_players[i]; if (tmp.PlayerConnection == e.Connection) { if (tmp.CurrentRoom != null) { tmp.CurrentRoom.Send("ROM:PLAYER:LEAVE:" + tmp.GetName(), null); tmp.CurrentRoom.RemovePlayer(tmp); } m_players.Remove(tmp); } } } }
public static NetMessage EncodeResponse(NetServer server) { if (server == null) throw new ArgumentNullException("server"); NetMessage msg = new NetMessage(server.Configuration.ServerName.Length + 4); msg.m_type = NetMessageType.Discovery; msg.Write((ushort)server.NumConnected); msg.Write((ushort)server.Configuration.MaximumConnections); msg.Write((string)server.Configuration.ServerName); return msg; }
public static NetMessage EncodeRequest(NetClient client) { if (client == null) throw new ArgumentNullException("client"); NetMessage msg = new NetMessage(); msg.m_type = NetMessageType.Discovery; msg.Write(client.Configuration.ApplicationIdentifier); return msg; }
internal static void HandleConnect(NetMessage connectMsg, NetServer server, IPEndPoint senderEndpoint) { NetMessage response; if (server.NumConnected >= server.Configuration.MaximumConnections) { // server full response = new NetMessage(NetMessageType.Handshake, "Server full".Length + 1); response.Write((byte)NetHandshakeType.Disconnected); response.Write("Server full"); server.SendSingleMessageAtOnce(response, null, senderEndpoint); return; } ushort remoteNow = connectMsg.ReadUInt16(); //server.Log.Debug("Setting remote clock based on guess of 50 ms lag..."); int remoteClockOffset = NetTime.CalculateOffset(NetTime.Now, remoteNow, 0.05); // assume 50ms... // read symmetric key int encSymKeyLen = connectMsg.ReadUInt16(); byte[] encSymKey = null; if (encSymKeyLen > 0) { encSymKey = connectMsg.ReadBytes(encSymKeyLen); } // read custom data int cdLen = (int)connectMsg.Read7BitEncodedUInt(); byte[] customData = null; if (cdLen > 0) { customData = connectMsg.ReadBytes(cdLen); } string failReason = null; bool ok = server.ApproveConnection(senderEndpoint, customData, out failReason); if (!ok) { if (!string.IsNullOrEmpty(failReason)) { // send disconnect reason; unencrypted, client can handle it because status is connecting response = new NetMessage(NetMessageType.Handshake, failReason.Length + 3); response.Write((byte)NetHandshakeType.Disconnected); response.Write(failReason); server.SendSingleMessageAtOnce(response, null, senderEndpoint); } // connection not approved return; } NetConnection connection = server.AddConnection(senderEndpoint, remoteClockOffset); if (connection == null) { return; // uh oh } if (encSymKeyLen > 0) { byte[] symKey = connection.m_encryption.DecryptRSA(encSymKey); if (symKey == null) { // send disconnect unencrypted, client can handle it because status is connecting string bye = "RSA failed; are you using correct public key?"; response = new NetMessage(NetMessageType.Handshake, bye.Length + 3); response.Write((byte)NetHandshakeType.Disconnected); response.Write(bye); server.SendSingleMessageAtOnce(response, null, senderEndpoint); server.Log.Warning("Failed to decrypt RSA encrypted symmetric key from " + senderEndpoint); return; } connection.m_encryption.SetSymmetricKey(symKey); server.Log.Debug("Received Connect containing key: " + Convert.ToBase64String(symKey)); } else { if (server.Configuration.UsesEncryption) { server.Log.Warning("Client tried to connect without encryption from " + senderEndpoint); // denied response = new NetMessage(NetMessageType.Handshake, "Encryption required".Length + 1); response.Write((byte)NetHandshakeType.Disconnected); response.Write("Encryption required"); server.SendSingleMessageAtOnce(response, null, senderEndpoint); return; } server.Log.Debug("Received Connect - using unencrypted connection!"); } // send connect response int bytesSent = SendConnectResponse(server, connection, senderEndpoint); if (connection != null) { // account for connectresponse connection.Statistics.PacketsSent++; connection.Statistics.MessagesSent++; connection.Statistics.BytesSent += bytesSent; } }
private void SendGameState(NetConnection Conn) { GameState++; NetMessage msg = new NetMessage(); string Message = "P" + Player.Location.X + "," + Player.Location.Y; Message = Message + "P"; foreach (Zombie Zombie in Zombies) { Message = Message + "Z" + Zombie.Location.X + "," + Zombie.Location.Y; } Message = Message + "P"; foreach (Bullet Bullet in Bullets) { Message = Message + "B" + Bullet.Location.X + "," + Bullet.Location.Y; } msg.Write(Message); //Sending the packet in Reliable is okay for this because its //one packet, When sending lots and lots of data you need to //set this to Unreliable. This will garentee it arrives but //not in a sepcific order. server.SendMessage(msg, Conn, NetChannel.Unreliable); }
internal static void ReplyPong(NetMessage pingMessage, NetConnection connection) { byte nr = pingMessage.ReadByte(6); NetMessage pong = new NetMessage(NetMessageType.PingPong, 3); pong.Write(true); // means pong pong.Write(false); // means NOT optimize info pong.Write(nr, 6); pong.WriteSendStamp(); connection.Parent.SendSingleMessageAtOnce(pong, connection, connection.RemoteEndpoint); }
internal override void HandlePacket(NetBuffer buffer, int bytesReceived, IPEndPoint sender) { double now = NetTime.Now; try { NetMessage msg; if (m_serverConnection == null || m_serverConnection.Status == NetConnectionStatus.Disconnected) { // // unconnected packet // msg = NetMessage.Decode(buffer); if (msg == null) { Log.Warning("Malformed NetMessage?"); return; // malformed? } Log.Verbose("Received unconnected message: " + msg); // discovery response? if (msg.m_type == NetMessageType.Discovery) { NetServerInfo info = NetDiscovery.DecodeResponse(msg, sender); if (ServerDiscovered != null) { ServerDiscovered(this, new NetServerDiscoveredEventArgs(info)); } return; } if (m_serverConnection != null && sender.Equals(m_serverConnection.RemoteEndpoint)) { // we have m_serverConnection, but status is disconnected Log.Warning("Received " + buffer.LengthBytes + " from server; but we're disconnected!"); return; } Log.Warning("Received " + buffer.LengthBytes + " bytes from non-server source: " + sender + "(server is " + m_serverConnection.RemoteEndpoint + ")"); return; } // decrypt in place if (m_serverConnection.m_encryption.SymmetricEncryptionKeyBytes != null) { byte[] savedBuffer = null; if (m_serverConnection.Status == NetConnectionStatus.Connecting) { // special case; save buffer in case we get unencrypted response savedBuffer = new byte[buffer.LengthBytes]; Array.Copy(buffer.Data, 0, savedBuffer, 0, buffer.LengthBytes); } bool ok = m_serverConnection.m_encryption.DecryptSymmetric(buffer); if (!ok) { // failed to decrypt; drop this packet UNLESS we're in a connecting state, // in which case the server may want to tell us something if (m_serverConnection.Status == NetConnectionStatus.Connecting) { // ok let this one thru unencrypted Array.Copy(savedBuffer, buffer.Data, savedBuffer.Length); } else { Log.Warning("Failed to decrypt packet from server!"); return; } } } m_serverConnection.m_lastHeardFromRemote = now; int messagesReceived = 0; int usrMessagesReceived = 0; int ackMessagesReceived = 0; while (buffer.ReadBitsLeft > 7) { msg = NetMessage.Decode(buffer); if (msg == null) { break; // done } messagesReceived++; msg.Sender = m_serverConnection; switch (msg.m_type) { case NetMessageType.Handshake: NetHandshakeType tp = (NetHandshakeType)msg.ReadByte(); if (tp == NetHandshakeType.Connect || tp == NetHandshakeType.ConnectionEstablished) { Log.Warning("Client received " + tp + "?!"); } else if (tp == NetHandshakeType.ConnectResponse) { if (m_serverConnection.Status != NetConnectionStatus.Connecting) { Log.Verbose("Received redundant ConnectResponse!"); break; } // Log.Debug("ConnectResponse received"); m_serverConnection.SetStatus(NetConnectionStatus.Connected, "Connected"); Log.Info("Connected to " + m_serverConnection.RemoteEndpoint); // initialize ping to now - m_firstSentConnect float initRoundtrip = (float)(now - m_serverConnection.m_firstSentHandshake); m_serverConnection.m_ping.Initialize(initRoundtrip); ushort remoteValue = msg.ReadUInt16(); m_serverConnection.RemoteClockOffset = NetTime.CalculateOffset(now, remoteValue, initRoundtrip); Log.Verbose("Initializing remote clock offset to " + m_serverConnection.RemoteClockOffset + " ms (roundtrip " + NetUtil.SecToMil(initRoundtrip) + " ms)"); NetMessage established = new NetMessage(NetMessageType.Handshake, 3); established.Write((byte)NetHandshakeType.ConnectionEstablished); established.WriteSendStamp(); SendSingleMessageAtOnce(established, m_serverConnection, m_serverConnection.RemoteEndpoint); } else { // Disconnected string reason = msg.ReadString(); m_serverConnection.SetStatus(NetConnectionStatus.Disconnected, reason); } break; case NetMessageType.Acknowledge: //Log.Debug("Received ack " + msg.SequenceChannel + "|" + msg.SequenceNumber); m_serverConnection.ReceiveAcknowledge(msg); ackMessagesReceived++; break; case NetMessageType.PingPong: bool isPong = msg.ReadBoolean(); bool isOptimizeInfo = msg.ReadBoolean(); if (isOptimizeInfo) { m_serverConnection.m_ping.HandleOptimizeInfo(now, msg); } else if (isPong) { if (m_serverConnection.Status == NetConnectionStatus.Connected) { m_serverConnection.m_ping.HandlePong(now, msg); } } else { NetPing.ReplyPong(msg, m_serverConnection); } break; case NetMessageType.User: case NetMessageType.UserFragmented: //Log.Debug("User message received; " + msg.m_buffer.LengthBytes + " bytes"); m_serverConnection.ReceiveMessage(now, msg); usrMessagesReceived++; break; case NetMessageType.Discovery: NetServerInfo info = NetDiscovery.DecodeResponse(msg, sender); if (ServerDiscovered != null) { ServerDiscovered(this, new NetServerDiscoveredEventArgs(info)); } break; default: Log.Warning("Client received " + msg.m_type + "?!"); break; } } // add statistics NetStatistics stats = m_serverConnection.Statistics; stats.PacketsReceived++; stats.MessagesReceived += messagesReceived; stats.UserMessagesReceived += usrMessagesReceived; stats.AckMessagesReceived += ackMessagesReceived; stats.BytesReceived += bytesReceived; } catch (Exception ex) { Log.Error("Failed to parse packet correctly; read/write mismatch? " + ex); } }
void server_StatusChanged(object sender, NetStatusEventArgs e) { if (e.Connection.Status == NetConnectionStatus.Connecting) { NetMessage msg = new NetMessage(); msg.Write("Hello Client, I See you are able to talk to me," + " I Can Talk to you Too!"); //Sending the packet in Reliable is okay for this because its //one packet, When sending lots and lots of data you need to //set this to Unreliable. This will garentee it arrives but //not in a sepcific order. server.SendMessage(msg, e.Connection, NetChannel.ReliableUnordered); } if (e.Connection.Status == NetConnectionStatus.Disconnected) { this.Window.Title = "Client Has Disconnected to You"; } }
void client_StatusChanged(object sender, NetStatusEventArgs e) { if (e.Connection.Status == NetConnectionStatus.Connected) { NetMessage msg = new NetMessage(); msg.Write("Hello Server! I Am Connected And Able To Communicate!"); client.SendMessage(msg, NetChannel.ReliableUnordered); } if (e.Connection.Status == NetConnectionStatus.Disconnected) { this.Window.Title = "We Were disconnected"; } }
internal static int SendConnect(NetClient client, IPEndPoint remoteEndpoint, byte[] customData) { if (client.Configuration.UsesEncryption) client.Log.Debug("Sending Connect containing key: " + Convert.ToBase64String(client.ServerConnection.m_encryption.SymmetricEncryptionKeyBytes)); else client.Log.Debug("Sending Connect - Unencrypted connection!"); NetMessage msg = new NetMessage(NetMessageType.Handshake, 3); msg.Write((byte)NetHandshakeType.Connect); msg.WriteSendStamp(); // encrypt symmetric key using server public key if (client.Configuration.UsesEncryption) { byte[] encryptedKey = client.ServerConnection.m_encryption.EncryptRSA(client.ServerConnection.m_encryption.SymmetricEncryptionKeyBytes); msg.Write((ushort)encryptedKey.Length); msg.Write(encryptedKey); } else { // request no encryption msg.Write((ushort)0); } if (customData == null || customData.Length < 1) { msg.Write7BitEncodedUInt(0); } else { msg.Write7BitEncodedUInt((uint)customData.Length); msg.Write(customData); } return client.SendSingleMessageAtOnce(msg, null, remoteEndpoint); }
private void SendInput(string Input) { if (client != null) { GameState++; NetMessage msg = new NetMessage(); ; msg.Write(Input); //Sending the packet in Reliable is okay for this because its //one packet, When sending lots and lots of data you need to //set this to Unreliable. This will garentee it arrives but //not in a sepcific order. client.SendMessage(msg, NetChannel.Unreliable); } }
internal static int SendConnectResponse(NetBase netBase, NetConnection clientConnection, IPEndPoint remoteEndpoint) { double now = NetTime.Now; ushort nowEnc = NetTime.Encoded(now); NetMessage response = new NetMessage(NetMessageType.Handshake, 3); response.Write((byte)NetHandshakeType.ConnectResponse); response.Write(nowEnc); clientConnection.m_firstSentHandshake = now; clientConnection.m_lastSentHandshake = now; return netBase.SendSingleMessageAtOnce(response, clientConnection, remoteEndpoint); }
/// <summary> /// Sends the given message using the given UDP delivery type. A client will send to the server, a server will broadcast. /// </summary> /// <param name="message">The message to be sent</param> /// <param name="deliveryType">The UDP delivery type</param> public void SendMessage(SpiderMessage message, NetChannel deliveryType) { NetMessage msg = new NetMessage(); msg.Write(message.ToByteArray()); spiderNet.SendMessage(msg, deliveryType); }
internal static int SendDisconnected(NetBase netBase, string reason, NetConnection connection) { NetMessage bye = new NetMessage(NetMessageType.Handshake, reason.Length + 3); bye.Write((byte)NetHandshakeType.Disconnected); bye.Write(reason); return netBase.SendSingleMessageAtOnce(bye, connection, connection.RemoteEndpoint); }
internal void SendOptimizeInfo(float roundtrip) { NetMessage ping = new NetMessage(NetMessageType.PingPong, 3); ping.Write(false); // meaningless ping.Write(true); // means optimize info ping.Write7BitEncodedUInt((uint)(roundtrip * 1000.0f)); m_connection.SendMessage(ping, NetChannel.Unreliable); }
internal static void HandleConnect(NetMessage connectMsg, NetServer server, IPEndPoint senderEndpoint) { NetMessage response; if (server.NumConnected >= server.Configuration.MaximumConnections) { // server full response = new NetMessage(NetMessageType.Handshake, "Server full".Length + 1); response.Write((byte)NetHandshakeType.Disconnected); response.Write("Server full"); server.SendSingleMessageAtOnce(response, null, senderEndpoint); return; } ushort remoteNow = connectMsg.ReadUInt16(); //server.Log.Debug("Setting remote clock based on guess of 50 ms lag..."); int remoteClockOffset = NetTime.CalculateOffset(NetTime.Now, remoteNow, 0.05); // assume 50ms... // read symmetric key int encSymKeyLen = connectMsg.ReadUInt16(); byte[] encSymKey = null; if (encSymKeyLen > 0) encSymKey = connectMsg.ReadBytes(encSymKeyLen); // read custom data int cdLen = (int)connectMsg.Read7BitEncodedUInt(); byte[] customData = null; if (cdLen > 0) customData = connectMsg.ReadBytes(cdLen); string failReason = null; bool ok = server.ApproveConnection(senderEndpoint, customData, out failReason); if (!ok) { if (!string.IsNullOrEmpty(failReason)) { // send disconnect reason; unencrypted, client can handle it because status is connecting response = new NetMessage(NetMessageType.Handshake, failReason.Length + 3); response.Write((byte)NetHandshakeType.Disconnected); response.Write(failReason); server.SendSingleMessageAtOnce(response, null, senderEndpoint); } // connection not approved return; } NetConnection connection = server.AddConnection(senderEndpoint, remoteClockOffset); if (connection == null) return; // uh oh if (encSymKeyLen > 0) { byte[] symKey = connection.m_encryption.DecryptRSA(encSymKey); if (symKey == null) { // send disconnect unencrypted, client can handle it because status is connecting string bye = "RSA failed; are you using correct public key?"; response = new NetMessage(NetMessageType.Handshake, bye.Length + 3); response.Write((byte)NetHandshakeType.Disconnected); response.Write(bye); server.SendSingleMessageAtOnce(response, null, senderEndpoint); server.Log.Warning("Failed to decrypt RSA encrypted symmetric key from " + senderEndpoint); return; } connection.m_encryption.SetSymmetricKey(symKey); server.Log.Debug("Received Connect containing key: " + Convert.ToBase64String(symKey)); } else { if (server.Configuration.UsesEncryption) { server.Log.Warning("Client tried to connect without encryption from " + senderEndpoint); // denied response = new NetMessage(NetMessageType.Handshake, "Encryption required".Length + 1); response.Write((byte)NetHandshakeType.Disconnected); response.Write("Encryption required"); server.SendSingleMessageAtOnce(response, null, senderEndpoint); return; } server.Log.Debug("Received Connect - using unencrypted connection!"); } // send connect response int bytesSent = SendConnectResponse(server, connection, senderEndpoint); if (connection != null) { // account for connectresponse connection.Statistics.PacketsSent++; connection.Statistics.MessagesSent++; connection.Statistics.BytesSent += bytesSent; } }
internal void SendPing(double now) { m_pingNrInProgress++; if (m_pingNrInProgress > 63) m_pingNrInProgress = 0; NetMessage ping = new NetMessage(NetMessageType.PingPong, 1); ping.Write(false); // means ping ping.Write(false); // means NOT optimize info ping.Write((byte)m_pingNrInProgress, 6); m_connection.Parent.SendSingleMessageAtOnce(ping, m_connection, m_connection.RemoteEndpoint); m_lastSentPing = now; }
public bool Send(String msg) { NetMessage outMsg = new NetMessage(); outMsg.Write(msg); return MMOServer.Server.SendMessage(outMsg, m_connection, NetChannel.ReliableUnordered); }