public static byte[] ConvertTcpMessageToBytes(TcpMessage message)
 {
     if (message != null)
     {
         //获取各部分长度
         int contentLength = Encoding.UTF8.GetByteCount(message.Content.Trim());
         int senderIdLength = Encoding.UTF8.GetByteCount(message.SenderId.Trim());
         int receiverIdLength = Encoding.UTF8.GetByteCount(message.ReceiverId.Trim());
         //初始化数组
         int totalLength = 10 + contentLength + senderIdLength + receiverIdLength;
         if (totalLength <= int.MaxValue)
         {
             byte[] messagebytes = new byte[totalLength];
             //设置各部分长度值
             messagebytes[0] = Convert.ToByte(message.MessageType);
             messagebytes[1] = (byte)senderIdLength;
             messagebytes[2] = (byte)receiverIdLength;
             messagebytes[3] = (byte)contentLength;
             //设置各部分内容
             int used = 10;
             Buffer.BlockCopy(Encoding.UTF8.GetBytes(message.SenderId), 0, messagebytes, used, senderIdLength);
             used += senderIdLength;
             Buffer.BlockCopy(Encoding.UTF8.GetBytes(message.ReceiverId), 0, messagebytes, used, receiverIdLength);
             used += receiverIdLength;
             Buffer.BlockCopy(Encoding.UTF8.GetBytes(message.Content), 0, messagebytes, used, contentLength);
             return messagebytes;
         }
     }
     return null;
 }
Exemple #2
0
 //处理消息
 private void DeliveryMessage(TcpMessage message, Socket clientSocket)
 {
     switch (message.MessageType)
     {
         case MType.Login:
             clientList.Add(message.SenderId, clientSocket);
             Thread receiceThread = new Thread(StartListenReceive);
             receiceThread.Start(message.SenderId);
             listenReceiveList.Add(message.SenderId, receiceThread);
             AddUserToUserTable(message.SenderId);
             SendUserList(message,clientSocket);
             SendAllUserLogInOrOutMessage(message);//通知所有人登陆消息
             dgvUserList.Invoke(new RefreshLB(RefreshUserList));
             break;
         case MType.Logout:
             CloseClient(message.SenderId);
             SendAllUserLogInOrOutMessage(message);//通知所有人退出消息
             RemoveUserFormUserTable(message.SenderId);
             dgvUserList.Invoke(new RefreshLB(RefreshUserList));
             break;
         case MType.Notice:
             break;
         case MType.Message:
             TcpMessager.SendTcpMessage((Socket)clientList[message.ReceiverId], message);
             break;
         case MType.Request:
             break;
         default:
             break;
     }
 }
        public static TcpMessage ConvertToTcpMessage(byte[] byteMessage)
        {
            if (byteMessage.Length >= 26)
            {
                TcpMessage tmEntity = new TcpMessage();
                //判断消息类型
                switch (byteMessage[0])
                {
                    case 1:
                        tmEntity.MessageType = MType.Login;
                        break;
                    case 2:
                        tmEntity.MessageType = MType.Logout;
                        break;
                    case 3:
                        tmEntity.MessageType = MType.Notice;
                        break;
                    case 4:
                        tmEntity.MessageType = MType.Message;
                        break;
                    case 5:
                        tmEntity.MessageType = MType.Request;
                        break;
                    case 6:
                        tmEntity.MessageType = MType.UserList;
                        break;
                    default:
                        break;
                }

                int senderIdLength = byteMessage[1];
                int receiverIdLength = byteMessage[2];
                int contentLength = byteMessage[3];
                int used = 10;
                //发送者
                tmEntity.SenderId = Encoding.UTF8.GetString(byteMessage, used, senderIdLength);
                used += senderIdLength;
                //接收者
                tmEntity.ReceiverId = Encoding.UTF8.GetString(byteMessage, used, receiverIdLength);
                used += receiverIdLength;
                //内容
                tmEntity.Content = Encoding.UTF8.GetString(byteMessage, used, contentLength);
                return tmEntity;
            }
            else
            {
                return null;
            }
        }
Exemple #4
0
 private void btnSend_Click(object sender, EventArgs e)
 {
     DataGridViewRow drv = dgvUserList.CurrentRow;
     if (drv!= null)
     {
         DataRow dr = (dgvUserList.SelectedRows[dgvUserList.CurrentRow.Index].DataBoundItem as DataRowView).Row;
         string rid = dr[0].ToString();
         if (!string.IsNullOrEmpty(rid))
         {
             TcpMessage tcmessage = new TcpMessage
             {
                 SenderId = txtUserId.Text.Trim(),
                 ReceiverId = rid,
                 MessageType = MType.Message,
                 Content = txtSendMessage.Text.Trim()
             };
             TcpMessager.SendTcpMessage(clientSocket, tcmessage);
         }
     }
     else
     {
         MessageBox.Show("未选择发送对象!");
     }
 }
        public static int SendTcpMessage(Socket socket, TcpMessage message)
        {
            if (socket.Connected)
            {
                try
                {
                    int i = socket.Send(ConvertTcpMessageToBytes(message));
                    return i;
                }
                catch (Exception)
                {

                }
                return 0;
            }
            else
            {
                return 0;
            }
        }
Exemple #6
0
        private void CloseClient()
        {
            string uid = txtUserId.Text;
              if (!string.IsNullOrEmpty(uid))
              {
                  Philo.Messager.Entity.TcpMessage msgEntity = new Philo.Messager.Entity.TcpMessage
                  {
                      SenderId = uid,
                      ReceiverId = "",
                      MessageType = MType.Logout,
                      Content = ""
                  };
                  int i = TcpMessager.SendTcpMessage(clientSocket, msgEntity);

                  if (clientSocket != null)
                  {
                      clientSocket.Close();
                  }
                  if (receiveThread != null)
                  {
                      receiveThread.Abort();
                  }
                  iClosed = true;
                  btnStart.Enabled = iClosed;
                  btnStop.Enabled = !iClosed;
                  btnSend.Enabled = !iClosed;
              }
              else
              {

              }
        }
Exemple #7
0
 //处理消息
 private void DeliveryMessage(TcpMessage message, Socket clientSocket)
 {
     switch (message.MessageType)
     {
         case MType.Login:
             AddUserToUserTable(message.SenderId);
             break;
         case MType.Logout:
             RemoveUserFormUserTable(message.SenderId);
             break;
         case MType.Notice:
             MessageBox.Show(message.Content);
             break;
         case MType.Message:
             txtMessage.Text = message.Content + "\n\r" + txtMessage.Text;
             break;
         case MType.Request:
             break;
         case MType.UserList:
             string[] uids = message.Content.Split(',');
             for (int i = 0; i < uids.Length; i++)
             {
                 if (!string.IsNullOrEmpty(uids[i]))
                 {
                     AddUserToUserTable(uids[i]);
                 }
             }
             break;
         default:
             break;
     }
     dgvUserList.Invoke(new RefreshLB(RefreshUserList));
 }
Exemple #8
0
        private void ConnectServer()
        {
            string uid = txtUserId.Text;
            if (!string.IsNullOrEmpty(uid))
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ipend = new IPEndPoint(IPAddress.Parse("192.168.0.136"), 39999);
                clientSocket.Connect(ipend);
                Philo.Messager.Entity.TcpMessage msgEntity = new Philo.Messager.Entity.TcpMessage {
                    SenderId = uid,
                    ReceiverId = "",
                    MessageType = MType.Login,
                    Content = ""
                };
                int i = TcpMessager.SendTcpMessage(clientSocket, msgEntity);
                receiveThread = new Thread(StartListenReceive);
                receiveThread.Start(clientSocket);
                txtUserId.ReadOnly = true;

                iClosed = false;
                btnStart.Enabled = iClosed;
                btnStop.Enabled = !iClosed;
                btnSend.Enabled = !iClosed;
            }
            else
            {
                MessageBox.Show("用户名不能为空!");
            }
        }
Exemple #9
0
 //给客户端发送用户列表
 private void SendUserList(TcpMessage message, Socket clientSocket)
 {
     string userstr = "";
     for (int i = 0; i < dtUserList.Rows.Count; i++)
     {
         userstr += dtUserList.Rows[i]["用户编码"].ToString() + ",";
     }
     TcpMessager.SendTcpMessage(clientSocket, new TcpMessage { SenderId = "0", ReceiverId = message.SenderId, MessageType = MType.UserList, Content = userstr });
 }
Exemple #10
0
 //给所有人发送有人登陆的消息
 private void SendAllUserLogInOrOutMessage(TcpMessage message)
 {
     foreach (var item in clientList)
     {
         if (!item.Key.Equals(message.SenderId))
         {
             TcpMessager.SendTcpMessage((Socket)item.Value, message);
         }
     }
 }