/// <summary> /// 初始化套接字并进行连接 /// </summary> public void Connect(RecvEventHandler onrecv) { recvHandler = onrecv;//接收到消息的处理函数 socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);// 创建一个TCP套接字 socket.Connect(ip, port);//连接指定IP地址 DebugHelper.Log("客户端套接字初始化IP地址为:"+ip+":"+port); }
public void Connect(string envMessage, RecvEventHandler onrecv) { // Create a TCP/IP socket recvHandler = onrecv; sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sender.Connect(ip, port); sender.Send(Encoding.ASCII.GetBytes(envMessage)); }
public void conn_client(RecvEventHandler onrecv) { if (recvHandler == null) { recvHandler = onrecv;//接收到消息的处理函数 } try { // 异步监听客户端的连接请求,立即返回,程序继续执行 socket.BeginAccept(AcceptCallBack, socket); } catch (System.Exception) { throw; } }
public bool unpack(byte[] data, RecvEventHandler recvHandler) { if (data.Length > 0) { foreach (byte bt in data) { dataBuffer.Add(bt); } while (true) { if (dataBuffer.Count < intSize * 3) { //DebugHelper.Log("数据包不够消息头大小"); break; } //解码消息正文大小 for (int i = 0; i < intSize; i++) { intBytes[i] = (byte)dataBuffer.GetRange(0, intSize)[i]; } int bodySize = System.BitConverter.ToInt32(intBytes, 0); //解码消息cmd大小 for (int i = 0; i < intSize; i++) { intBytes[i] = (byte)dataBuffer.GetRange(4, intSize)[i]; } int cmd = System.BitConverter.ToInt32(intBytes, 0); //解码消息recv大小 for (int i = 0; i < intSize; i++) { intBytes[i] = (byte)dataBuffer.GetRange(8, intSize)[i]; } int recv = System.BitConverter.ToInt32(intBytes, 0); //判断是否超过一个消息长度,处理分包情况 if (dataBuffer.Count < intSize * 3 + bodySize) { //DebugHelper.Log("数据包不够消息正文大小"); break; } // 解码消息正文 byte[] bodyBytes = new byte[bodySize]; for (int i = 0; i < bodySize; i++) { bodyBytes[i] = (byte)dataBuffer.GetRange(12, bodySize)[i]; } string _Jsonbody = Encoding.UTF8.GetString(bodyBytes); //DebugHelper.Log("解码得到消息正文:"+ _Jsonbody); var _body = JsonConvert.DeserializeObject <dynamic>(_Jsonbody); //DebugHelper.Log("JsonConvert转换得到消息正文:" + _body); // 处理消息正文 if (recvHandler != null) { DebugHelper.Log("接收到消息包->cmd:" + (MsgCmd)cmd + " bodySize:" + bodySize.ToString() + " recv:" + recv.ToString(), Color.green); recvHandler(cmd, _body, recv);// 交给处理消息的接口 } else { DebugHelper.Log("无法分发消息包,可能消息处理函数为空"); } // 移除已经处理的消息,处理粘包情况 dataBuffer.RemoveRange(0, bodySize + intSize * 3); } return(true); } else { return(false); } }