private void BeginClientConnect(IAsyncResult ar) { try { // Retrieve the socket from the state object. var client = (Socket)ar.AsyncState; // Complete the connection. client.EndConnect(ar); // start receiving var packet = new ConnectionsControllerformation { Socket = client, Payload = new byte[DefaultPacketSize] }; client.BeginReceive(packet.Payload, 0, DefaultPacketSize, SocketFlags.None, ReceiveCallback, packet); OnClientConnected(); } catch { // ignored } }
private void ReceiveCallback(IAsyncResult ar) { try { // Retrieve the state object and the handler socket // from the asynchronous state object. var packet = (ConnectionsControllerformation)ar.AsyncState; // the client. var client = packet.Socket; // Read data from the socket. var bytesRead = client.EndReceive(ar); if (bytesRead == 0) { return; } // There might be more data, so store the data received so far. // state.Sb.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead)); // we received it all. HandleReceived(client, packet.Payload, bytesRead); // Not all data received. Get more. packet = new ConnectionsControllerformation { Socket = client, Payload = new byte[DefaultPacketSize] }; client.BeginReceive(packet.Payload, 0, DefaultPacketSize, 0, ReceiveCallback, packet); } catch (ArgumentException) { // seen happening when we receive something after disconnecting. // the heartbeat will reemove the socket. } catch (SocketException) { } catch (ObjectDisposedException) { // the client socket might have been disconnected. } }
private void BeginServerAccept(IAsyncResult ar) { try { // Get the socket that handles the client request. // var listener = (Socket)ar.AsyncState; // Create the state object. var client = _socket.EndAccept(ar); try { // then listen for a new connection right away. // unless of course we are disconnected. // in that case, don't listen for anything else. _socket.BeginAccept(BeginServerAccept, _socket); // register this socket RegisterClientSocket(client); var packet = new ConnectionsControllerformation { Socket = client, Payload = new byte[DefaultPacketSize] }; client.BeginReceive(packet.Payload, 0, DefaultPacketSize, SocketFlags.None, ReceiveCallback, packet); } catch { client.Disconnect(true); } } catch { // ignored } }