private void client_OnServerConnected(object sender, TcpServerConnectedEventArgs e) { //链接成功,向服务器发送学校编号。 SocketMsgBase baseMsg = new SocketMsgBase(); baseMsg.LinkType = "1"; baseMsg.MsgType = TcpMsgDataType.ClientToken; baseMsg.Sender = schoolNum; baseMsg.SubSystem = TcpSeatManageSubSystem.SocketClient; client.Send(ByteSerializer.ObjectToByte(baseMsg)); }
/// <summary> /// 推送消息处理 /// </summary> /// <param name="msg"></param> private void PubshMsg(SocketMsgBase msg) { try { if (msg is SocketRequest) { SocketRequest srMsg = msg as SocketRequest; appPush.MsgPush((string)srMsg.Parameters[0]); Console.WriteLine("{0:M} {1:t}:推送用户消息:{2}", DateTime.Now, DateTime.Now, (string)srMsg.Parameters[0]); } } catch (Exception ex) { WriteLog.Write(string.Format("PubshMsg执行遇到异常:{0},异常来自:{1}", ex.Message, ex.Source)); } }
void server_OnMsgReceived(string uid, SocketMsgBase e) { try { SocketMsgBase msg = e; if (msg.SubSystem == TcpSeatManageSubSystem.SocketClient && msg.MsgType == TcpMsgDataType.ClientToken) { if (schoolNums.ContainsKey(msg.Sender)) { schoolNums[msg.Sender] = uid; } else { schoolNums.Add(msg.Sender, uid); } Console.WriteLine("{0:M} {1:t}:学校{2}已建立连接", DateTime.Now, DateTime.Now, msg.Sender); // SeatManage.SeatManageComm.WriteLog.Write(schoolLinkLog, string.Format("学校{0}已连接,Ip地址:{1}", msg.Sender, uid)); if (OnSchoolConnectionHandler != null) { OnSchoolConnectionHandler(msg.Sender, uid); } } else { if (OnReceivedMsg != null) { OnReceivedMsg(msg); } switch (msg.MsgType) { case TcpMsgDataType.Relay: RelaySocketMsg(uid, msg); break; case TcpMsgDataType.MsgPush: PubshMsg(msg); break; } } } catch (Exception ex) { WriteLog.Write(string.Format("消息处理失败:{0},异常来自:{1}", ex.Message, ex.Source)); } }
/// <summary> /// 转发socket消息 , /// </summary> /// <param name="uid">请求的目标ID。</param> /// <param name="msg">如果msg类型为Request,即客户端请求学校,需要转发给学校。否则为学校响应客户端的请求。</param> private void RelaySocketMsg(string uid, SocketMsgBase msg) { try { msg.Sender = uid; if (schoolNums.ContainsKey(msg.Target)) { server.Send(schoolNums[msg.Target], ByteSerializer.ObjectToByte(msg)); Console.WriteLine("{0:M} {1:t}:转发给目标{2},地址为:{3}", DateTime.Now, DateTime.Now, msg.Target, schoolNums[msg.Target]); } else { if (msg is SocketRequest) { Console.WriteLine("{0:M} {1:t}:请求的目标{2}不存在", DateTime.Now, DateTime.Now, msg.Target); SocketResponse response = new SocketResponse(); response.SubSystem = msg.SubSystem; response.MethodName = msg.MethodName; response.Sender = response.Target; response.Target = response.Sender; response.ErrorMsg = "学校没有连接"; server.Send(uid, ByteSerializer.ObjectToByte(response)); } else if (msg is SocketResponse) { // Console.WriteLine("消息回复给{0}", msg.Target); Console.WriteLine("{0:M} {1:t}:消息回复给{2}", DateTime.Now, DateTime.Now, msg.Target); server.Send(msg.Target, ByteSerializer.ObjectToByte(msg)); } } } catch (Exception ex) { WriteLog.Write(string.Format("RelaySocketMsg执行遇到异常:{0},异常来自:{1}", ex.Message, ex.Source)); } }