private void Receive(object o) { Socket socketReceive = o as Socket; try { while (true) { //判断接受buffer是否为空 byte[] buffer = new byte[1024 * 1024 * 2]; int len = socketReceive.Receive(buffer); if (len == 0) { //如果得到字符为空,则代表没有接收到数据 break; } else { WriteLog("接收到来自服务器的数据"); byte[] bufferReceive = new byte[len]; for (int i = 0; i < len; i++) { bufferReceive[0] = buffer[0]; } Message messageReceive = SerializationUnit.DeserializeObject(buffer) as Message; string fromFriendID = messageReceive.FromClient;//消息来自哪一个客户端 #region 根据返回的类型进行消息操作 switch (messageReceive.Sign) { #region 000为来自服务器的数据 case "000": break; #endregion #region 101客户端与客户端之间的普通聊天 case "101": //p判断该聊天窗口是否存在,存在则直接调用 if (this.dicChatWindow.ContainsKey(fromFriendID)) { dicChatWindow[fromFriendID].Dispatcher.Invoke( new Action( delegate { dicChatWindow[fromFriendID].ChangeTxtMsgLog( string.Format("{0}: {1}\n{2}\n", dicChatWindow[fromFriendID].Title.ToString(), DateTime.Now.ToString(), messageReceive.Msg)); } ) ); //写日志 WriteLog(string.Format("fromClient:{1}\nMessage:{1}", fromFriendID, messageReceive.Msg)); } else { //该窗口不存在,则打开新的窗口,在进行操作 MessageBox.Show("未完成的工作"); } break; #endregion #region 201 接受图片的事件 case "201": if (this.dicChatWindow.ContainsKey(fromFriendID)) { dicChatWindow[fromFriendID].Dispatcher.Invoke( new Action( delegate { dicChatWindow[fromFriendID].ChangeTxtMsgLog( string.Format("{0}:\n{1}\n", dicChatWindow[fromFriendID].Title.ToString(), "接受图片的事件")); } ) ); SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.InitialDirectory = @"C:\Users\58317\Desktop"; saveFileDialog.Title = "请选择要保存的文件"; saveFileDialog.Filter = "所有文件|*.*"; saveFileDialog.ShowDialog(); string path = saveFileDialog.FileName; using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) { fileStream.Write(messageReceive.BufferFile, 0, messageReceive.BufferFile.Length); } WriteLog(string.Format("fromClient:{1}\nMessage:{1}", fromFriendID, "接受图片的事件")); } else { //该窗口不存在,则打开新的窗口,在进行操作 MessageBox.Show("未完成的工作"); } break; #endregion #region 301 客户端对客户端的请求事件 case "301": if (this.dicChatWindow.ContainsKey(fromFriendID)) { #region 判断请求的类型,分别执行不同的操作 switch (messageReceive.Request) { case 1: dicChatWindow[fromFriendID].Dispatcher.Invoke( new Action( delegate { dicChatWindow[fromFriendID].ChangeTxtMsgLog( string.Format("来自{0}: {1}\n请求震动事件\n", dicChatWindow[fromFriendID].Title.ToString(), DateTime.Now.ToString())); dicChatWindow[fromFriendID].ZD(); } ) ); //写日志 // WriteLog(string.Format("fromClient:{1}\n请求震动事件", fromFriendID)); break; } #endregion } else { //该窗口不存在,则打开新的窗口,在进行操作 MessageBox.Show("未完成的工作"); } break; #endregion default: break; } } #endregion //进行内存回收 GC.Collect(); } } catch (Exception ex) { MessageBox.Show("接收服务端发送的消息出错:" + ex.ToString()); } }
/// <summary> /// 接收TCP数据包,解析并处理 /// </summary> /// <param name="ar"></param> private static void ReceiveCallback(IAsyncResult ar) { lastRecieveTime = DateTime.Now; StateObject state = (StateObject)ar.AsyncState; Socket client = state.socket; try { int bytesRead = client.EndReceive(ar); //对端gracefully关闭一个连接 if (bytesRead <= 0) { CloseClientSocket(); return; } byte[] destinationArray = new byte[bytesRead]; Array.Copy(state.buffer, destinationArray, bytesRead); List <byte[]> lstrec; lock (s2Lock) { lstrec = handleRawBytes(destinationArray); } try { foreach (byte[] destinationArr in lstrec) { StructData sd = (StructData)seru.DeserializeObject(destinationArr); if (sd.cmd == 0x66) { ThreadPool.QueueUserWorkItem(SavePdfBytesToFile, sd); } //[{ // "TaskID": 0, // "SpecificationID": 0, // "MachineID": 23, // "MachineTypeID": 2, // "EmployeeID_Main": "abc123", // "EmployeeID_Assistant": "abc123", // "Start_Axis_No": "abc123", // "CodeNumber": "abc123", // "Axis_No": "abc123", // "Printcode": "abc123", // "CollectedTime": "abc123", // "MaterialRFID": 0 //}] if (sd.datamain != null && sd.datamain.Length > 0) { byte[] byteString = Encoding.UTF8.GetBytes(sd.datamain); using (MemoryStream stream = new MemoryStream(byteString)) { DataContractJsonSerializer dataMainSerializer = new DataContractJsonSerializer(typeof(List <DataMain>)); OnHandleDataMain((List <DataMain>)dataMainSerializer.ReadObject(stream)); } } //[{ // "ParameterCodeID": 42, // "CollectedValue": "2.161", // "CollectedTime": "2016/12/16 17:24:22", // "Axis_No": "abc123", // "MachineID": 13 //}] if (sd.datadetail != null && sd.datadetail.Length > 0) { byte[] byteString = Encoding.UTF8.GetBytes(sd.datadetail); using (MemoryStream stream = new MemoryStream(byteString)) { DataContractJsonSerializer dataDetailSerializer = new DataContractJsonSerializer(typeof(List <DataDetail>)); OnHandleDataDetail((List <DataDetail>)dataDetailSerializer.ReadObject(stream)); } } } } catch { /* 非Socket异常,忽略 */ } client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } catch { lock (s2Lock) { Array.Clear(s2, 0, s2.Length); s2 = new byte[0]; } CloseClientSocket(); } }
private void Receive(Object o) { Socket socketReceive = o as Socket; string userid = ""; try { while (true) { //将接收到额buffer转为Message byte[] buffer = new byte[1024 * 1024 * 2]; int len = socketReceive.Receive(buffer); if (len == 0) { break; } else { //反序列化,将buffer转化为类 WriteLog(string.Format("接收到来自客户端:{0} 的数据", socketReceive.RemoteEndPoint)); byte[] bufferReceive = new byte[len]; for (int i = 0; i < len; i++) { bufferReceive[0] = buffer[0]; } Message messageReceive = SerializationUnit.DeserializeObject(buffer) as Message; string fromClient = messageReceive.FromClient; //从哪里发过来 string toClient = messageReceive.ToClient; //要发到哪去 userid = messageReceive.Sign; //做一个标记 #region 根据协议处理数据 switch (messageReceive.Sign) { #region 001 完成用户ID与端口的绑定 case "001": //数据逻辑处理 dicSocket.Add(messageReceive.FromClient, socketReceive); //将用户id与ip地址绑定 //UI处理以及日志 this.txtLog.Dispatcher.Invoke(receiveCallBack, string.Format("登录用户ID:{0}\n登录的ip地址:{1}", fromClient, socketReceive.RemoteEndPoint.ToString())); //this.cmbSocket.Dispatcher.Invoke(setCmbCallBack, messageReceive.FromClient);//ui控制 WriteLog(string.Format("登录用户ID:{0}\n登录的ip地址:{1}", fromClient, socketReceive.RemoteEndPoint.ToString())); break; #endregion #region 101 完成客户端数据的转发 case "101": if (dicSocket.ContainsKey(fromClient)) { //将对象重新序列化 byte[] sendByte = SerializationUnit.SerializeObject(messageReceive); dicSocket[toClient].Send(sendByte); //写日志 this.txtLog.Dispatcher.Invoke(receiveCallBack, string.Format("fromClient:{0}\ntoClient:{1}\nMessage:{2}\n", fromClient, toClient, messageReceive.Msg)); WriteLog(string.Format("fromClient:{0}\ntoClient:{1}\nMessage:{2}\n", fromClient, toClient, messageReceive.Msg)); } else { MessageBox.Show("服务器找不到该用户"); } break; #endregion #region 201 发送文件的事件 case "201": if (dicSocket.ContainsKey(fromClient)) { //将对象重新序列化 byte[] sendByte = SerializationUnit.SerializeObject(messageReceive); dicSocket[toClient].Send(sendByte); //写日志 this.txtLog.Dispatcher.Invoke(receiveCallBack, string.Format("fromClient:{0}\ntoClient:{1}\nMessage:{2}\n", fromClient, toClient, "转发文件成功")); WriteLog(string.Format("fromClient:{0}\ntoClient:{1}\nMessage:{2}\n", fromClient, toClient, "转发文件成功")); } else { MessageBox.Show("服务器找不到该用户"); } break; #endregion case "301": if (dicSocket.ContainsKey(fromClient)) { //将对象重新序列化 byte[] sendByte = SerializationUnit.SerializeObject(messageReceive); //转发数据 dicSocket[toClient].Send(sendByte); //写日志 this.txtLog.Dispatcher.Invoke(receiveCallBack, string.Format("fromClient:{0}\ntoClient:{1}\nRequest:{2}\n", fromClient, toClient, messageReceive.Request)); WriteLog(string.Format("fromClient:{0}\ntoClient:{1}\nRequest:{2}\n", fromClient, toClient, messageReceive.Request)); } else { MessageBox.Show("服务器找不到该用户"); } break; default: break; } #endregion //进行内存回收 GC.Collect(); } } } catch (Exception ex) { dicSocket.Remove(userid); //MessageBox.Show("接收服务端发送的消息出错:" + ex.ToString()); } }