public void Receive() { if (!IsConnected()) { throw new Exception("Client not connected"); } var state = new ClientStateObject(); state.workSocket = _listener; _listener.BeginReceive(state.buffer, 0, ClientStateObject.BufferSize, SocketFlags.None, ReceiveCallback, state); }
public static void Send(int clientId, string data) { var state = new ClientStateObject(); var clientState = _clients.TryGetValue(clientId, out state) ? state : null; if (clientState == null || clientState.isConnected == false) { throw new Exception("Client doesnt exisit or is not connected"); } var bytes = Encoding.UTF8.GetBytes(data); clientState.workSocket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(SendCallback), clientState); }
private static void OnClientConnect(IAsyncResult ar) { _resetEvent.Set(); var clientStateObject = new ClientStateObject(); clientStateObject.isConnected = true; var socket = (Socket)ar.AsyncState; lock (m_locker) { clientStateObject.Id = !_clients.Any() ? 1 : _clients.Keys.Max() + 1; _clients.Add(clientStateObject.Id, clientStateObject); } try { clientStateObject.workSocket = socket.EndAccept(ar); clientStateObject.workSocket.BeginReceive(clientStateObject.buffer, 0, ClientStateObject.BufferSize, SocketFlags.None, RecieveCallback, clientStateObject); } catch (ObjectDisposedException) { // Connection is likely closed } }