private void AcceptCallback(IAsyncResult result) { TcpConnectionInfo connection = new TcpConnectionInfo(); try { Socket s = (Socket)result.AsyncState; connection.Socket = s.EndAccept(result); connection.Buffer = new byte[255]; connection.RemoteAddress = connection.Socket.RemoteEndPoint.ToString(); connection.RemoteEndPoint = (IPEndPoint)connection.Socket.RemoteEndPoint; _connections[((IPEndPoint)connection.Socket.RemoteEndPoint).Address.ToString()] = connection; if (clientConnected != null) { clientConnected(connection); } connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), connection); _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), result.AsyncState); } catch (SocketException e) { CloseConnection(connection, e); } catch (ObjectDisposedException) { } catch (Exception ex) { CloseConnection(connection, ex); } }
private void CloseConnection(TcpConnectionInfo ci, Exception ex) { if (ci != null && ci.Socket != null) { try { TcpConnectionInfo removed = null; _connections.TryRemove(ci.RemoteEndPoint.Address.ToString(), out removed); ci.Socket.Close(); } catch { } if (clientDisconnected != null) { clientDisconnected(ci, ex); } } }
public void Send(IPEndPoint endPoint, byte[] data) { if (endPoint != null) { if (_connections.ContainsKey(endPoint.Address.ToString())) { TcpConnectionInfo connection = _connections[endPoint.Address.ToString()]; try { connection.Socket.Send(data); } catch (SocketException e) { CloseConnection(connection, e); } catch (ObjectDisposedException) { } catch (Exception) { } } } else { foreach (var connection in _connections) { try { connection.Value.Socket.Send(data); } catch (SocketException e) { CloseConnection(connection.Value, e); } catch (ObjectDisposedException) { } catch (Exception) { } } } }
private void ReceiveCallback(IAsyncResult result) { TcpConnectionInfo connection = (TcpConnectionInfo)result.AsyncState; try { int bytesRead = connection.Socket.EndReceive(result); if (0 != bytesRead) { if (dataReceived != null) { byte[] data = new byte[bytesRead]; Buffer.BlockCopy(connection.Buffer, 0, data, 0, bytesRead); dataReceived(connection, data); } connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), connection); } else { CloseConnection(connection, null); } } catch (SocketException e) { CloseConnection(connection, e); } catch (ObjectDisposedException) { } catch (Exception ex) { CloseConnection(connection, ex); } }