public void SendCtrlMess() { if (mySocket == null) { mySocket = ConnectSocket.getSocketInstance(); } byte[] messByte = new byte[13]; //帧头 messByte[0] = 0x54; messByte[1] = 0x43; //流水号 messByte[2] = 0x00; messByte[3] = 0x00; messByte[4] = 0x00; messByte[5] = 0x00; // 设备类型 的灯 messByte[6] = 0x01; //设备编号 messByte[7] = 0x01; //功能码 messByte[8] = 0x01; //数据长度 messByte[9] = 0x00; //CRC16校验 messByte[10] = 0x54; messByte[11] = 0x54; //帧尾 messByte[12] = 0xED; mySocket.SendMess(messByte); }
public void Disconnect() { //ServerForm server = new ServerForm(); if (AcceptSocket != null) { AcceptSocket.Close(); AcceptSocket.Dispose(); } if (ConnectSocket != null) { ConnectSocket.Close(); ConnectSocket.Dispose(); } /* * ServerForm server = new ServerForm(); * * if (server.AcceptSocket != null) * { * server.AcceptSocket.Close(); * server.AcceptSocket.Dispose(); * } * if (server.ConnectSocket != null) * { * server.ConnectSocket.Close(); * server.ConnectSocket.Dispose(); * } */ }
public static ConnectSocket getSocketInstance() { if (instance == null) { instance = new ConnectSocket(); } return(instance); }
void Start() { mySocket = ConnectSocket.getSocketInstance(); InitSetting(); ClearStateShow(); UpdateControlStateShow(); }
public static SendDataController getInstance() { if (instance == null) { instance = new SendDataController(); instance.socket = ConnectSocket.getSocketInstance(); } return(instance); }
private void StartConnect(SocketAsyncEventArgs iSocketAsyncEventArgs) { bool willRaiseEvent = ConnectSocket.ConnectAsync(iSocketAsyncEventArgs); if (!willRaiseEvent) { ProcessConnect(iSocketAsyncEventArgs); } }
//不处理退出 public void PlayerGameClick() { ProtocolNetRequest req = new ProtocolNetRequest(); req.cmd = (int)NetRequestType.ROOMOWNERREADYSTARTGAME; RoomOwnerReadyStartGame data = new RoomOwnerReadyStartGame(); data.fd = ownerFd; req.roomOwnerReadyStartGame = data; ConnectSocket.getSocketInstance().sendMSG(PBCSerialize.Serialize(req)); }
public static SocketQueue getInstance() { if (instance == null) { instance = new SocketQueue(); instance.socket = ConnectSocket.getSocketInstance(); instance.socket.setReiviceCallback(instance.changeBytes); instance.queue = new Queue <ProtocolNetResponse>(); } return(instance); }
public void ReloadGameScene() { ProtocolNetRequest req = new ProtocolNetRequest(); req.cmd = (int)NetRequestType.PLAYERRELOADSCENE; PlayerReLoadScene reload = new PlayerReLoadScene(); reload.fd = GameGlobalData.fd; req.playerReloadScene = reload; ConnectSocket.getSocketInstance().sendMSG(PBCSerialize.Serialize(req)); }
public virtual void Disconnect(Action <string> disConnectCallback = null) { //string localIpEndPort = ConnectSocket.LocalEndPoint.ToString(); if (ConnectSocket != null && Identity != null && ConnectSocket.Connected) { ConnectSocket.BeginDisconnect(false, ar => { disConnectCallback?.Invoke(Identity); //LogMsg(localIpEndPort,remoteIpEndPort,$"disconnect socket remote {remoteIpEndPort} local {localIpEndPort}"); }, null); } }
IEnumerator StartGameRequest() { yield return(new WaitForSeconds(3)); ProtocolNetRequest req = new ProtocolNetRequest(); req.cmd = (int)NetRequestType.ROOMOWNERSTARTGAME; RoomOwnerStartGame data = new RoomOwnerStartGame(); data.fd = ownerFd; req.roomOwnerStartGame = data; ConnectSocket.getSocketInstance().sendMSG(PBCSerialize.Serialize(req)); }
public void StartReceiveAsync() { try { bool willRaiseEvent = ConnectSocket.ReceiveAsync(ReceiveEventArgs); //投递接收请求 if (!willRaiseEvent) { PacketProtocol.ReceiveComplate(null, ReceiveEventArgs); } } catch (Exception e) { loger.Fatal(e); } }
public override void Connect() { new Thread(() => { using (ConnectSocket) { Socket = ConnectSocket.Accept(); StartReadingMessages(); } }) { IsBackground = true }.Start(); }
public static void OnApplicationQuit() { if (ConnectSocket.getSocketInstance().isConnect()) { ConnectSocket.getSocketInstance().Close(); } if (UDPSocket.Instance.isInit) { UDPSocket.Instance.Close(); } #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif }
// Use this for initialization void Start() { socket = ConnectSocket.getSocketInstance(); SocketQueue.getInstance().setCallback(getPbcResponse); createRoomPanel = gameObject.transform.parent.Find("CreateRoomPanel").GetComponent <Transform>(); roomOwnerText = transform.Find("name").GetComponent <Text>(); roomOwner = PlayerPrefs.GetString("UserName"); roomOwnerText.text = roomOwner; organizePanelEvent = gameObject.transform.parent.Find("OrganizePanel").GetComponent <OrganizePanelEvent>(); roomPanelEvent = gameObject.transform.parent.Find("RoomPanel").GetComponent <RoomPanelEvent>(); needFlush = true; deltaTime = 0.0f; maxDeltaTime = 10f; type = transform.parent.Find("Type").GetComponent <Text>(); createRoomPanel.Find("roomName").GetComponent <InputField>().text = "123"; createRoomPanel.Find("maxManCount").GetComponent <InputField>().text = "2"; }
public void ButtonClick() { ProtocolNetRequest req = new ProtocolNetRequest(); req.cmd = (int)NetRequestType.JOINROOM; JoinRoom joinRoom = new JoinRoom(); joinRoom.fd = GameGlobalData.fd; joinRoom.roomOwnerFd = ownerFd; GameGlobalData.roomOwnerFd = ownerFd; GameGlobalData.roomOwnerName = OwnerNameText.text; GameGlobalData.roomName = RoomNameText.text; GameGlobalData.currentMan = this.manCount; GameGlobalData.maxManCount = this.maxManCount; req.joinRoom = joinRoom; ConnectSocket.getSocketInstance().sendMSG(PBCSerialize.Serialize(req)); }
//private Queue<byte[]> GetPackage(byte[] receiveByte) //{ // List<byte> package =new List<byte>(); // var queePackage = new Queue<byte[]>(); // int msgLength; // if (_prePartialReceiveByte != null && _prePartialReceiveByte.Length > 0) // { // package= package.Concat(_prePartialReceiveByte).ToList(); // } // package = package.Concat(receiveByte).ToList(); // int rIndex = package.IndexOf(0x0A); // if (rIndex == -1)//当前包也是同一个消息中的一部分 // {//处理断包问题 // if (_prePartialReceiveByte != null && _prePartialReceiveByte.Length > 0) // { // var temp = _prePartialReceiveByte.ToList(); // temp.AddRange(receiveByte); // _prePartialReceiveByte = temp.ToArray(); // } // else // { // _prePartialReceiveByte = receiveByte; // } // return queePackage; // } // if (package.Count >= 6) //包最小长度6,过滤掉0数据长度包 // { // byte[] byts = package.GetRange(0, 4).ToArray(); // msgLength = BitConverter.ToInt32(byts,0); // } // else // { // _prePartialReceiveByte = null; // return queePackage; // } // int takeLength = 0; // while (takeLength < package.Count) // { // var takeBytes = package.Skip(takeLength + 4).Take(msgLength - 4).ToArray(); // takeLength += takeBytes.Length + 4; // if (takeBytes.Length + 4 == msgLength && takeBytes[takeBytes.Length - 2] == 0x0D && // takeBytes[takeBytes.Length - 1] == 0x0A) // { // queePackage.Enqueue(takeBytes.Take(takeBytes.Length - 2).ToArray()); // } // else break; // var currindex = package.IndexOf(0x0A, takeLength); // if (currindex > 0 && currindex + 1 < package.Count) // { // byte[] byts = package.GetRange(takeLength, 4).ToArray(); // msgLength = BitConverter.ToInt32(byts, 0); // } // else break; // } // if (takeLength < package.Count) // { // _prePartialReceiveByte = package.GetRange(takeLength, package.Count - takeLength).ToArray(); // } // else // { // _prePartialReceiveByte = null; // } // return queePackage; //} #endregion #region Send /// <summary> /// 发送字节数组,针对websocket协议本身就定义了前2,4,8字节为数据长度,所以不用加上自定义的数据帧长度了 /// </summary> /// <param name="byteData"></param> /// <param name="sendCallBack">发送数据当前回调</param> public virtual void Send(byte[] byteData, Action <SocketConnection> sendCallBack = null) { try { #if DEBUG LogMsg(ConnectSocket.LocalEndPoint.ToString(), ConnectSocket.RemoteEndPoint.ToString(), $"to {ConnectSocket.RemoteEndPoint} data [{BitConverter.ToString(byteData)}]\r\n"); #endif Sktconfig?.BeforeSend?.Invoke(byteData, this);//发送之前的操作 var sendBytes = BitConverter.GetBytes(byteData.Length + 6).Concat(byteData).ToArray().Concat(new byte[] { 0x0D, 0x0A }).ToArray(); if (SocketConnectType == SocketConnectType.WebSocket) { long byteLength = byteData.Length; byte[] header; if (byteLength < 126) { header = new byte[] { 0x82, 0x00 }; Array.Copy(BitConverter.GetBytes((byte)byteLength & 0x7F), 0, header, 1, 1); } else if (byteLength <= ushort.MaxValue) { header = new byte[] { 0x82, 0x7E, 0x00, 0x00 }; var shortLength = Convert.ToUInt16(byteLength); var b1 = Convert.ToByte(shortLength / 256); var b2 = Convert.ToByte(shortLength % 256); Array.Copy(new [] { b1, b2 }, 0, header, 2, 2); } else { header = new byte[] { 0x82, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Array.Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(byteLength)), 0, header, 2, 2); } sendBytes = header.Concat(byteData).ToArray(); sendBytes = new DataFrame(sendBytes).GetBytes(); } ConnectSocket.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallback, sendCallBack); } catch (SocketException sktex) { SocketException(ConnectSocket, sktex); } catch (Exception ex) { Exception(ex); } }
public static void Quit() { #if UNITY_EDITOR if (ConnectSocket.getSocketInstance().isConnect()) { ConnectSocket.getSocketInstance().Close(); } if (UDPSocket.Instance.isInit) { UDPSocket.Instance.Close(); } UnityEditor.EditorApplication.isPlaying = false; #elif UNITY_WEBPLAYER Application.OpenURL(webplayerQuitURL); #else Application.Quit(); #endif }
private void _DisConnect() { Pool.TcpServer.OnDisConnect(this); ConnectDateTime = null; if (ConnectSocket != null) { try { ConnectSocket.Shutdown(SocketShutdown.Both); } catch (Exception e) { //日志记录 Pool.TcpServer.Loger.Fatal(string.Format("CloseClientSocket Disconnect client {0} error, message: {1}", ConnectSocket, e.Message)); } ConnectSocket.Dispose(); ConnectSocket = null; } }
public void Disconnect() { try { if (isInit) { ConnectSocket?.Shutdown(System.Net.Sockets.SocketShutdown.Both); //if(dispose) // DisconnectIt?.Invoke(this); } } catch (ObjectDisposedException) { } catch (Exception) { } }
/// <summary> /// 接收数据 /// </summary> public virtual void ReceiveData(Action <byte[], SocketConnection> receiveCallback = null) { try { var srb = new SocketReceiveBack() { Buffer = new byte[BufferSize], ReceiveCallback = receiveCallback }; ConnectSocket.BeginReceive(srb.Buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, srb); } catch (SocketException sktex) { SocketException(ConnectSocket, sktex); } catch (Exception ex) { Exception(ex); } }
protected void ProcessReceive() { if (ConnectSocket == null) { return; } ActiveTime = DateTime.Now; if (ReceiveEventArgs.BytesTransferred > 0 && ReceiveEventArgs.SocketError == SocketError.Success) { int offset = ReceiveEventArgs.Offset; int count = ReceiveEventArgs.BytesTransferred; if (count > 0) //处理接收数据 { //如果处理数据返回失败,则断开连接 if (!ProcessReceive(ReceiveEventArgs.Buffer, offset, count)) { Close(); } else //否则投递下次介绍数据请求 { bool willRaiseEvent = ConnectSocket.ReceiveAsync(ReceiveEventArgs); //投递接收请求 if (!willRaiseEvent) { ProcessReceive(); } } } else { bool willRaiseEvent = ConnectSocket.ReceiveAsync(ReceiveEventArgs); //投递接收请求 if (!willRaiseEvent) { ProcessReceive(); } } } else { Close(); } }
void Start() { perDeltaTime = 0.05f; curDeltaTime = 0f; StartNetSend = false; UdpTick = true; socket = ConnectSocket.getSocketInstance(); udpSocket = UDPChannel.Instance; if (!udpSocket.isInit) { udpSocket.init(); } SocketQueue.getInstance().setCallback(ReceiveResponseData); dispatch = new GameNetMessageDispatch(); dispatch.logicNetSwap = this; udpSocket.setCallback(dispatch.DispatchMessage); udpSocket.setSendCallback(dispatch.DispatchMessage); GameGlobalData.player.GetComponent <PlayerBehaviourCollector>().logicSwap = this; StartCoroutine(SendStartInfo()); }
public void DisConnect() { OnDisConnect(this); if (ConnectSocket != null) { try { ConnectSocket.Shutdown(SocketShutdown.Both); } catch (Exception e) { //日志记录 loger.Fatal(string.Format("CloseClientSocket Disconnect client {0} error, message: {1}", ConnectSocket, e.Message)); } ConnectSocket.Dispose(); ConnectSocket = null; } Clear(); ReceiveEventArgs.Dispose(); SendEventArgs.Dispose(); }
public void DisConnect() { if (OnDisConnect != null) { OnDisConnect(null, this); } //释放引用,并清理缓存,包括释放协议对象等资源 PacketProtocol.Clear(); if (ConnectSocket != null) { try { ConnectSocket.Shutdown(SocketShutdown.Both); } catch (Exception e) { loger.Fatal(e); } } ConnectSocket.Close(); ConnectSocket = null; }
//清理session public void Clear() { //释放引用,并清理缓存,包括释放协议对象等资源 PacketProtocol.Clear(); SessionData.Clear();//清理session数据 if (ConnectSocket == null) { return; } try { ConnectSocket.Shutdown(SocketShutdown.Both); } catch (Exception e) { //日志记录 loger.Fatal(string.Format("CloseClientSocket Disconnect client {0} error, message: {1}", ConnectSocket, e.Message)); } ConnectSocket.Close(); ConnectSocket = null; Server = null; }