public void Sendpacket(UdpPacket packet, UdpSession session) { packet.Sequence = ++session.outSequence; byte[] sendBuffer = packet.ToByteArray(false, Crypter); System.Diagnostics.Debug.WriteLineIf(Debug, "Udp " + packet.ToString() + " send to " + new IPEndPoint(session.address, session.port).ToString()); serverSocket.SendTo(sendBuffer, new IPEndPoint(session.address, session.port)); }
public bool IsValidUDPSession(UdpSession session) { if (session.address.ToString() != ((IPEndPoint)socket.RemoteEndPoint).Address.ToString()) { return(false); } if (session.sessionId != ConnectionId) { return(false); } if (obj == null) { return(false); } return(true); }
public int RegisterSession(string remoteIp, IConnectedObjectUdp obj) { UdpSession session = new UdpSession(); session.address = IPAddress.Parse(remoteIp); session.obj = obj; obj.UdpSession = session; lock (sessions) { while (true) { session.sessionId = StrongRandom.NextInt(int.MinValue, int.MaxValue); if (!sessions.ContainsKey(session.sessionId)) { sessions.Add(session.sessionId, session); break; } } } return(session.sessionId); }
void ReceiveFromCallback(IAsyncResult ar) { try { EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int bytesRead = 0; try { bytesRead = serverSocket.EndReceiveFrom(ar, ref remoteEP); } catch (ObjectDisposedException) { return; } catch (SocketException ex) { System.Diagnostics.Debug.WriteLineIf(Debug, string.Format("Socket exception at UDPServer.ReceiveFromCallback(" + remoteEP.ToString() + "): " + ex.Message + ". " + ex.StackTrace)); System.Diagnostics.Debug.Assert(false, ex.Message); StartReceive(); return; } IPEndPoint remoteEP_IP = (IPEndPoint)remoteEP; UdpPacket packet = UdpPacket.Parse(buffer, true, Crypter); StartReceive(); UdpSession session = null; lock (sessions) { if (!sessions.ContainsKey(packet.UdpSessionId)) { throw new UdpException(string.Format("Received invalid session {2} from {0}:{1}", remoteEP_IP.Address, remoteEP_IP.Port, packet.UdpSessionId)); } session = sessions[packet.UdpSessionId]; } if (session.port > 0 && session.port != remoteEP_IP.Port) { throw new UdpException(string.Format("Session {0} suddenly changed the port", packet.UdpSessionId)); } session.port = remoteEP_IP.Port; if (packet.Sequence <= session.inSequence) //drop { return; } session.inSequence = packet.Sequence; if (session.inSequence >= uint.MaxValue) { session.inSequence = 0; } if (session.obj == null) { throw new UdpException(string.Format("Session {0} object is null", packet.UdpSessionId)); } session.lastData = DateTime.UtcNow; session.obj.Dispatch(packet); System.Diagnostics.Debug.WriteLineIf(Debug, "Udp " + packet.ToString() + " received from " + remoteEP_IP.ToString()); } catch (UdpException ex) { System.Diagnostics.Debug.WriteLineIf(Debug, ex.Message + "\n" + ex.StackTrace); } }