private void StartReceiveCallback(IAsyncResult asyncResult) { Socket socket = asyncResult.AsyncState as Socket; try { socket.EndReceive(asyncResult); buffer = new byte[8192]; int received = socket.Receive(buffer, buffer.Length, 0); if (received <= 0) { Console.WriteLine("No Bytes received, disconnecting.."); throw new SocketException(); } if (buffer.Length > received) { Array.Resize(ref buffer, received); } OnDataReceivedEvent?.Invoke(this, buffer); socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, StartReceiveCallback, null); } catch { OnClientDisconnectedEvent?.Invoke(this); CloseConnection(); } }
private void ConnectionLostRaise(EndPointId id, TcpClient client) { if (clients.ContainsKey(id) || lobbyClients.ContainsKey(id)) { Console.WriteLine("An unexpected disconnection, source: " + ((IPEndPoint)client.Client.RemoteEndPoint).ToString()); clients.Remove(id); lobbyClients.Remove(id); OnClientDisconnectedEvent?.Invoke(id); } }
private void TryToReceive() { IPEndPoint remoteIp = new IPEndPoint(IPAddress.Any, port); while (true) { try { dataReceived = server.Receive(ref remoteIp); object arg = Encoding.Unicode.GetString(dataReceived); object[] args; args = arg.ToString().Split(argSplitter); OnReceivedEvent?.Invoke(args, remoteIp.Address.ToString(), remoteIp.Port); } catch (Exception e) { OnClientDisconnectedEvent?.Invoke(remoteIp.Address.ToString(), remoteIp.Port); Console.WriteLine(e); } } }
public void Send(object[] args, string ip, int port) { IPAddress ipA = IPAddress.Parse(ip); IPEndPoint remoteIp = new IPEndPoint(ipA, port); string data = ""; foreach (object arg in args) { data += arg + argSplitter.ToString(); } data = data.Substring(0, data.Length - 1); try { byte[] messageToSend = Encoding.Unicode.GetBytes(data); server.Send(messageToSend, messageToSend.Length, (IPEndPoint)remoteIp); } catch (Exception e) { OnClientDisconnectedEvent?.Invoke(ip, port); Console.WriteLine(e); } }
public override void OnServerDisconnect(NetworkConnection conn) { base.OnServerDisconnect(conn); OnClientDisconnectedEvent?.Invoke(conn); }
/// <summary> /// Triggered when the client is disconnected from the remote end point. /// </summary> protected void OnDisconnected() { OnClientDisconnectedEvent?.Invoke(); }
/// <summary> /// Triggered when a client disconnects from the server. /// </summary> /// <param name="connection"></param> private void OnClientDisconnected(NetUser connection) { OnClientDisconnectedEvent?.Invoke(connection); }