/// <summary> /// Close socket /// </summary> public virtual bool Close() { if (Interlocked.CompareExchange(ref isInClosing, ActiveSentinel, NoneSentinel) == NoneSentinel) { try { WorkSocket.Shutdown(SocketShutdown.Both); } catch (SocketException) { } catch (Exception ex) { var stackFrameString = StackTrace.GetStackFrameString(); logger.Error("ExSocket EndPoint:{0} Close error:{1} stack:{2}", RemoteEndPoint, ex, stackFrameString); } finally { WorkSocket.Close(); } return(true); } return(false); }
private void CheckPsw(WorkSocket workSocket, String content) { DeviceInfo device = (DeviceInfo)JsonConvert.DeserializeObject(content, typeof(DeviceInfo)); device.remoteIp = workSocket.remoteIp; workSocket.remoteDeviceId = device.deviceId; String key = device.deviceId; if (sessions.ContainsKey(key)) { SendMsgToClient(workSocket, AppProtocol.json_type_notify_back_check_fail, "连接失败,您已经连接!"); return; } if (device.accessCode.Equals(myPsw)) { sessions[key] = workSocket; updateInfo(device, MyConfig.INT_CLIENT_ONLINE); SendMsgToClient(workSocket, AppProtocol.json_type_notify_back_check_success, "连接成功!"); } else { updateInfo(device, MyConfig.INT_CLIENT_ADD_TEMP); SendMsgToClient(workSocket, AppProtocol.json_type_notify_back_check_fail, "密码校验失败!"); } }
void clearActiveStatus() { updateInfo(activeId, MyConfig.INT_CLIENT_FREE); serverWorkStatus = MyConfig.SERVER_WORK_STATUS_FREE; activeSocket = null; activeId = ""; }
private void ProccessByte(WorkSocket workSocket, byte[] payLoad) { if (activeId.Equals(workSocket.remoteDeviceId) && (workSocket == activeSocket)) { UpdateShadowContainer(payLoad); } }
private void ProcessBuffers() { if (!WorkSocket.Connected) { Buffer = null; return; } if (Buffer != null) { lock (Buffer) { if (Buffer.Position > 0) { var payload = Buffer.ToBuffer(); WorkSocket.Send(payload, 0, payload.Length, System.Net.Sockets.SocketFlags.None, out var error); { if (error != System.Net.Sockets.SocketError.SocketError) { Buffer.Position = 0; } } } } } }
internal void Close() { if (_Listener != null) { Server.SendMessageTask task = _Listener.GetTask(this); int queueCount; lock (_QueueLockObj) { _Closed = true; queueCount = _Queue.Count; } task.IncTotalQueueCount(0 - queueCount); } try { WorkSocket.Close(); } catch { } }
private void closeShadowForm(WorkSocket workSocket) { if (activeSocket == workSocket && activeId.Equals(workSocket.remoteDeviceId) && serverWorkStatus == MyConfig.SERVER_WORK_STATUS_SHADOW) { clearActiveStatus(); updateInfo("Close shadow container!", MyConfig.INT_DELETE_DESK_CONTAINER); } }
private void startMouseMode(WorkSocket workSocket) { serverWorkStatus = MyConfig.SERVER_WORK_STATUS_MOUSE; activeId = workSocket.remoteDeviceId; activeSocket = workSocket; updateInfo(activeId, MyConfig.INT_CLIENT_BUSY); SendMsgToClient(workSocket, AppProtocol.json_type_notify_back_mouse_open_ok, "连接成功!"); }
public void CloseSocket() { if (WorkSocket != null) { WorkSocket.Shutdown(SocketShutdown.Both); WorkSocket.Close(); } }
/// <summary> /// /// </summary> public void Close() { try { WorkSocket.Shutdown(SocketShutdown.Both); } catch { } WorkSocket.Close(); }
/// <summary> /// 重新开始接收数据 /// </summary> /// <exception cref="ArgumentNullException"></exception> /// private void RefreshReceive() { AsyncStateOne state = new AsyncStateOne(); state.WorkSocket = WorkSocket; state.UdpEndPoint = new IPEndPoint(IPAddress.Any, 0); state.BytesContent = new byte[ReceiveCacheLength]; //WorkSocket.BeginReceiveFrom(state.BytesHead, 0, 8, SocketFlags.None, ref state.UdpEndPoint, new AsyncCallback(ReceiveAsyncCallback), state); WorkSocket.BeginReceiveFrom(state.BytesContent, 0, ReceiveCacheLength, SocketFlags.None, ref state.UdpEndPoint, new AsyncCallback(AsyncCallback), state); }
private void closeMouseMode(WorkSocket workSocket) { if (workSocket == activeSocket && serverWorkStatus == MyConfig.SERVER_WORK_STATUS_MOUSE) { updateInfo(activeId, MyConfig.INT_CLIENT_FREE); serverWorkStatus = MyConfig.SERVER_WORK_STATUS_FREE; activeSocket = null; activeId = ""; } }
void CreateShadowContainer(WorkSocket workSocket, String content) { deskWidth = Int32.Parse(content.Split('|')[0]); deskHeight = Int32.Parse(content.Split('|')[1]); activeId = workSocket.remoteDeviceId; serverWorkStatus = MyConfig.SERVER_WORK_STATUS_SHADOW; activeSocket = workSocket; updateInfo(workSocket.remoteDeviceId, MyConfig.INT_CLIENT_BUSY); //更新设备列表 updateInfo("Start shadow container!", MyConfig.INT_CREATE_DESK_CONTAINER); //创建容器 SendMsgToClient(workSocket, AppProtocol.json_type_notify_back_shadow_open_ok, "连接成功"); }
private void closeMouseSession(WorkSocket workSocket) { if (workSocket == activeSocket && serverWorkStatus == MyConfig.SERVER_WORK_STATUS_MOUSE) { updateInfo(activeId, MyConfig.INT_CLIENT_OFFLINE); serverWorkStatus = MyConfig.SERVER_WORK_STATUS_FREE; activeSocket = null; activeId = ""; Console.WriteLine(activeId); } }
internal void AsyncSend(byte[] buf) { //while (BufferLength > 1024 * 1024) //{ // System.Threading.Thread.Sleep(1); //} //IncBufferLength(buf.Length); //WorkSocket.BeginSend(buf, 0, buf.Length, SocketFlags.None, // new AsyncCallback(Async_Send), WorkSocket); WorkSocket.Send(buf, SocketFlags.None); }
void socket_ReceiveMessage(WorkSocket workSocke, byte[] pToken, byte[] obj) { byte[] serverToken = mySocket.getToken(); for (int i = 0; i < serverToken.Length; i++) { if (serverToken[i] != pToken[i]) { updateInfo("密钥异常,关闭连接:" + workSocke.session.RemoteEndPoint.ToString(), MyConfig.INT_UPDATEUI_TXBOX); return; } } dataProccess(workSocke, obj); }
public void StartWorking() { byte[] buffer = new byte[8197]; try { WorkSocket.BeginReceive(buffer, 5, 8192, SocketFlags.None, Received, buffer); } catch (ObjectDisposedException) { ShutdownSocket(); OnTransmissionError(); } }
private void SendAcknowledgment(ApplicationProtocolHeader head) { _Logger.Debug("Sending header acknowledgment"); try { WorkSocket.Send(head.WrapHeaderData()); } catch (Exception) { _Logger.Error("Error sending header acknowledgment"); CloseConnectionGracefully(); } }
private void dataProccess(WorkSocket workSocket, byte[] obj) { byte[] payLoad = new byte[obj.Length - 1]; System.Array.Copy(obj, 1, payLoad, 0, payLoad.Length); switch (obj[0]) { case MyConfig.INT_APP_PROTOCOL_JSON: ProccessJson(workSocket, payLoad); break; case MyConfig.INT_APP_PROTOCOL_BYTE: ProccessByte(workSocket, payLoad); break; } }
/// <summary> /// Execute functions according to the internal state /// </summary> /// <param name="microseconds"> Time in microseconds allowed to wait for operation </param> public void ExecuteState(int microseconds) { switch (_ConnectionState) { case TCPConnectionState.ReceivingHeader: //Try catch here is because the previous MessageHandler might have closed the socket already. //flagging it as disposed. try { if (WorkSocket.Poll(microseconds, SelectMode.SelectRead)) { ReceiveHeaderData(); } } catch (ObjectDisposedException) { CloseConnectionGracefully(); //throw; } break; case TCPConnectionState.ReceivingMessageData: try { if (WorkSocket.Poll(microseconds, SelectMode.SelectRead)) { ReceiveMessageData(); } } catch (ObjectDisposedException) { CloseConnectionGracefully(); //throw; } break; default: break; } }
void mySocket_ErrLog(WorkSocket workSocket, int code, string obj) { switch (code) { case AppProtocol.ERR_CODE_FLAG: updateInfo(workSocket.remoteIp + ":" + workSocket.remotePort + "," + code + "," + obj, MyConfig.INT_UPDATEUI_TXBOX); break; case AppProtocol.ERR_CODE_RECEIVE_DATA: updateInfo(workSocket.remoteIp + ":" + workSocket.remotePort + "," + code + "," + obj, MyConfig.INT_UPDATEUI_TXBOX); break; case AppProtocol.ERR_CODE_HEALTH_CHECKED: updateInfo(workSocket.remoteIp + ":" + workSocket.remotePort + "," + code + "," + obj, MyConfig.INT_UPDATEUI_TXBOX); break; } }
internal void Close() { if (mIOSendEventArgs == null || mIOSendEventArgs == null) { return; } try { var socket = WorkSocket; if (socket != null) { WorkSocket.Shutdown(SocketShutdown.Both); WorkSocket.Close(); } var dataToken0 = (AsyncUserToken)mIOSendEventArgs.UserToken; if (dataToken0 != null) { dataToken0.Reset(true); dataToken0.tcpConn = null; } var dataToken1 = (AsyncUserToken)mIOReceiveEventArgs.UserToken; if (dataToken1 != null) { dataToken1.Reset(true); dataToken1.tcpConn = null; } } catch (Exception) { } finally { mIOSendEventArgs.AcceptSocket = null; server.GetIOArgPool().Push(mIOSendEventArgs); mIOSendEventArgs = null; mIOReceiveEventArgs.AcceptSocket = null; server.GetIOArgPool().Push(mIOReceiveEventArgs); mIOReceiveEventArgs = null; this.server = null; mState = NetState.Disconnect; } }
private void repeatConn(WorkSocket workSocket, String content) { DeviceInfo device = (DeviceInfo)JsonConvert.DeserializeObject(content, typeof(DeviceInfo)); String key = device.deviceId; workSocket.remoteDeviceId = device.deviceId; device.remoteIp = workSocket.remoteIp; sessions[key] = workSocket; updateInfo(device, MyConfig.INT_CLIENT_ONLINE); if (device.status.Equals("2")) { CreateShadowContainer(workSocket, device.userId); } if (device.status.Equals("3")) { startMouseMode(workSocket); } }
void socket_sessionClosed(WorkSocket workSocket) { String key = workSocket.remoteDeviceId; if (!sessions.ContainsKey(key)) { return; } if (key.Equals(activeId)) { closeShadowForm(workSocket); closeMouseSession(workSocket); } if (workSocket == sessions[key]) { sessions.Remove(key); updateInfo(key, MyConfig.INT_CLIENT_OFFLINE); updateInfo("close:" + workSocket.remoteIp + ":" + workSocket.remotePort, MyConfig.INT_UPDATEUI_TXBOX); } }
internal SCB(Server.NTcpListener listener, Socket workSocket) { _Listener = listener; lock (_SCBID_LOCK) { Id = _SCB_ID++; } this._CurState = State.Sync0; this.WorkSocket = workSocket; _MSGHead[0] = 0xA5; _MSGHead[1] = 0xA5; RemoteIPEndPoint = (IPEndPoint)workSocket.RemoteEndPoint; //AddTCB(this); _MStream = new System.IO.MemoryStream(MStreamCapacity); WorkSocket.BeginReceive(_Buffer, 0, _Buffer.Length, SocketFlags.None, new AsyncCallback(Async_Receive), WorkSocket); }
public void SetReceiveCallback(AsyncCallback callback) { WorkSocket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, callback, this); }
void mySocket_AcceptClient(WorkSocket workSocke) { updateInfo("新的连接:" + workSocke.session.RemoteEndPoint.ToString(), MyConfig.INT_UPDATEUI_TXBOX); }
/// <summary> /// 发送字符串数据到服务器 /// </summary> /// <param name="customer">用户自定义的标记数据</param> /// <param name="data">字符串数据</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="SocketException"></exception> /// <exception cref="ObjectDisposedException"></exception> public void SendMessage(NetHandle customer, string data) { WorkSocket.SendTo(NetSupport.CommandBytes(customer, KeyToken, data), ServerEndPoint); }
/// <summary> /// send message from queue. only server side use it. /// </summary> /// <returns>how many messages has been send</returns> internal int SendFromQueue() { lock (_QueueLockObj) { if (_Closed) { return(0); } int queueCount = _Queue.Count; try { Server.SendMessageTask task = _Listener.GetTask(this); task.IncTotalQueueCount(0 - queueCount); while (_Queue.Count > 0) { Message message = _Queue.Dequeue(); message.WriteToStream(_MStream); IncBufferLength(0 - message.Data.Length); if (_MStream.Length > MStreamCapacity / 2) { try { AsyncSend(_MStream.GetBuffer(), 0, (int)_MStream.Length); } catch (Exception e) { _Queue.Clear(); try { if (WorkSocket.Connected) { WorkSocket.Close(); } } catch { } finally { //Server.NTcpListener.RemoteSCB(this); } WriteError("SendFromQueue", e); return(queueCount); } if (_MStream.Length > MStreamCapacity) { _MStream = new System.IO.MemoryStream(MStreamCapacity); } else { _MStream.SetLength(0); _MStream.Position = 0; } } } if (_MStream.Length > 0) { try { AsyncSend(_MStream.GetBuffer(), 0, (int)_MStream.Length); } catch (Exception e) { _Queue.Clear(); try { if (WorkSocket.Connected) { WorkSocket.Close(); } } catch { } finally { //Server.NTcpListener.RemoteSCB(this); } WriteError("SendFromQueue", e); return(queueCount); } if (_MStream.Length > MStreamCapacity) { _MStream = new System.IO.MemoryStream(MStreamCapacity); } else { _MStream.SetLength(0); _MStream.Position = 0; } } } catch (Exception e) { WriteError("SendFromQueue", e); } return(queueCount); } }
private void Async_Receive(IAsyncResult ar) { Socket s = (Socket)ar.AsyncState; int read = 0; try { read = s.EndReceive(ar); if (read == 0) { //Remote connection call shut down. if (!SocketConnected) { //Disconnected OnDisconnect(this); } else { try { WorkSocket.Close(); } catch { } OnDisconnect(this); WriteError("EndReceive", new Exception("Remote shut down")); } return; } } catch (Exception e) { if (!SocketConnected) { //Disconnected OnDisconnect(this); } else { WriteError("EndReceive", e); } return; } int offset = 0; List <Event.ReceiveEventArgs> recvArgsList = null; if (OnBatchReceive != null) { recvArgsList = new List <NTCPMSG.Event.ReceiveEventArgs>(); } while (offset < read) { if (_CurState == State.Data) { int copyLen = Math.Min(read - offset, _CurLength - _CurDataOffset); Array.Copy(_Buffer, offset, _CurData, _CurDataOffset, copyLen); offset += copyLen; _CurDataOffset += copyLen; if (_CurDataOffset >= _CurData.Length) { if (OnBatchReceive != null) { recvArgsList.Add(new NTCPMSG.Event.ReceiveEventArgs( this.Id, this.RemoteIPEndPoint, _CurFlag, _CurEvent, _CurCableId, _CurChannel, _CurData)); } if (OnReceive != null) { try { OnReceive(this, _CurFlag, _CurEvent, _CurCableId, _CurChannel, _CurData); } catch (Exception e) { WriteError("OnReceive", e); } } _CurState = State.Sync0; } if (offset >= read) { break; } } _CurState = NextState(_Buffer[offset++]); } if (_CurState == State.Data && _CurLength == 0) { if (_CurDataOffset >= _CurData.Length) { if (OnBatchReceive != null) { recvArgsList.Add(new NTCPMSG.Event.ReceiveEventArgs( this.Id, this.RemoteIPEndPoint, _CurFlag, _CurEvent, _CurCableId, _CurChannel, _CurData)); } if (OnReceive != null) { try { OnReceive(this, _CurFlag, _CurEvent, _CurCableId, _CurChannel, new byte[0]); } catch (Exception e) { WriteError("OnReceive", e); } } _CurState = State.Sync0; } } if (OnBatchReceive != null) { OnBatchReceive(this, recvArgsList); } if (read > 0) { try { s.BeginReceive(_Buffer, 0, _Buffer.Length, SocketFlags.None, new AsyncCallback(Async_Receive), WorkSocket); } catch (Exception e) { if (!SocketConnected) { //Disconnected OnDisconnect(this); } else { WriteError("BeginReceive", e); } } } }