/// <summary> /// Close the socket associated with the client. /// </summary> /// <param name="e">SocketAsyncEventArg associated with the completed send/receive operation.</param> public void CloseClientSocket(SocketAsyncEventArgs e) { StateObject token = e.UserToken as StateObject; if (token != null) { try { int RemovedConnections = DeviceData.RemoveConnectionsByDeviceId(token.DeviceId); Console.WriteLine("RemovedConnections: {0}", RemovedConnections); DeviceData.UpdateDeviceOffline(token.DeviceId); this.CloseClientSocket(token.Connection); token.Dispose(); e.UserToken = null;// token; Interlocked.Decrement(ref this.numConnectedSockets); Console.WriteLine("A client has been disconnected from the server. There are {0} clients connected to the server", this.numConnectedSockets); log.DebugFormat("A client has been disconnected from the server. There are {0} clients connected to the server", this.numConnectedSockets); // Update to DB DeviceData.UpdateNumOfDevicesConnected(Protocol: token.ProtocolName, Port: token.Port, Count: this.numConnectedSockets); e.SetBuffer(new Byte[this.bufferSize], 0, this.bufferSize); // Free the SocketAsyncEventArg so they can be reused by another client. this.readWritePool.Push(e); // Decrement the counter keeping track of the total number of clients connected to the server. this.semaphoreAcceptedClients.Release(); } catch (Exception ex) { } } }
private void Terminate(StateObject state = null) { if (state == null) { Debug.Print("Terminating.."); States.CompleteAdding(); m_allDone.Set(); while (States.TryTake(out state)) { Terminate(state); } Debug.Assert(States.IsCompleted); } else { Terminate(state.WorkSocket); state.Dispose(); } }
private void StartSend(StateObject state, SocketAsyncEventArgs args) { if (args == null) { args = new SocketAsyncEventArgs(); args.SetBuffer(state.stream.GetBuffer(), 0, (int)state.stream.Length); args.Completed += SentCallback; args.UserToken = state; } try { _socket.SendAsync(args); } catch (Exception ex) { state.Dispose(); OnSent(false, ex, args.SocketError); } }
private void StartReceive(SocketAsyncEventArgs args, StateObject state) { if (args == null) { args = new SocketAsyncEventArgs(); args.Completed += ReceiveCallback; args.UserToken = state; args.SetBuffer(state.buffer, 0, state.buffer.Length); } try { if (!state.handler.ReceiveAsync(args)) { ReceiveCallback(null, args); } } catch (Exception ex) { state.Dispose(); OnReceived(false, ex, args.SocketError, null); } }
public void ReadCallback(IAsyncResult ar) { log.InfoFormat("{0}/ReadCallback:", _fileNm); StateObject state = (StateObject)ar.AsyncState; state.lastReadTime = DateTime.UtcNow; try { log.DebugFormat("{0}/ReadCallback: state.workSocket.Connected: {1}", _fileNm, state.workSocket.Connected); if (state.workSocket.Connected) { state.deviceInfo.TrackerDataActionTime = DateTime.UtcNow; state.deviceInfo.TrackerIp = state.workSocket.RemoteEndPoint.ToString(); // Read data from the client socket. int bytesRead = state.workSocket.EndReceive(ar); log.DebugFormat("{0}/ReadCallback: bytesRead: {1}", _fileNm, bytesRead); if (bytesRead == 0) { state.Dispose(); return; } //TODO memory will increase in this case state.deviceInfo.RawData = new byte[bytesRead]; state.deviceInfo.RawData = state.buffer.Take(bytesRead).ToArray(); state.deviceInfo = Protocol.Parser.Process(this.ProtocolParser, state.deviceInfo); log.DebugFormat("{0}/ReadCallback: Protocol.Protocol.Process Done", _fileNm); if (state.deviceInfo.ToSendRawData != null && state.deviceInfo.ToSendRawData.Count() > 0) { log.InfoFormat("{0}/ReadCallback: ToSendRawData", _fileNm); // TODO sent to device Send(state.workSocket, state.deviceInfo.ToSendRawData); state.deviceInfo.ToSendRawData = null; } log.DebugFormat("{0}/ReadCallback: Payload: {1}, ParserStatus: {2}", _fileNm, state.deviceInfo.Payload, state.deviceInfo.ParserStatus); if (state.deviceInfo.Payload != null && state.deviceInfo.Payload.Length > 0 && state.deviceInfo.ParserStatus == ProtocolParserStatus.Initialized) { log.DebugFormat("{0}/ReadCallback: Unparsed junk closing connection", _fileNm); // Unparsed junk stored in Payload, // Close the connection to avoid payload increase in its size state.Dispose(); } else { if (isListening) { state.workSocket.BeginReceive(state.buffer, 0, state.BufferSize, 0, new AsyncCallback(ReadCallback), state); } } } else { state.Dispose(); } } catch (SocketException sException) { // Can be handled only by exception: Client disconnected log.ErrorFormat("{0}/ReadCallback: SocketException Client: {1}, Closed Exception: {2}", _fileNm, state.workSocket.RemoteEndPoint, sException); state.Dispose(); } catch (Exception ex) { log.ErrorFormat("{0}/ReadCallback: {1}", _fileNm, ex); } }
public void Close() { ClosePeer(); _stateObject.Dispose(); }