//退出按钮点击事件 private void buttonClose_Click(object sender, EventArgs e) { //如果还未建立连接 if (socketClient == null) { this.Close(); return; } //如果已经建立连接 try { byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(userName, 0, userName.Length) + "退出了聊天室"); commum.Message msg = new commum.Message(); msg.message = arrClientSendMsg; msg.ipAddress = userName; arrClientSendMsg = PackCodec.Serialize <commum.Message>(msg); SendMsg(arrClientSendMsg); socketClient.Shutdown(SocketShutdown.Both); this.Close(); } catch (SocketException) { txtMsg.AppendText("当前未连接\r\n"); this.Close(); return; } catch (NullReferenceException) { return; } }
//发送按钮 private void button1_Click(object sender, EventArgs e) { byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(txtCMsg.Text.Trim()); commum.Message msg = new commum.Message(); msg.message = arrClientSendMsg; msg.ipAddress = userName; arrClientSendMsg = PackCodec.Serialize <commum.Message>(msg); SendMsg(arrClientSendMsg); }
private void buttonLogin_Click(object sender, EventArgs e) { byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(userName, 0, userName.Length) + "进入了聊天室"); commum.Message msg = new commum.Message(); msg.message = arrClientSendMsg; msg.ipAddress = userName; arrClientSendMsg = PackCodec.Serialize <commum.Message>(msg); SendMsg(arrClientSendMsg); btnSend.Enabled = true; buttonLogin.Enabled = false; }
/// <summary> /// 接收服务端发来信息的方法 /// </summary> private void RecMsg() { byte[] arrRecMsg = new byte[1024]; while (true) //持续监听服务端发来的消息 { commum.Message msg = new commum.Message(); //将客户端套接字接收到的数据存入内存缓冲区, 并获取其长度 try { Array.Clear(arrRecMsg, 0, 1024); socketClient.Receive(arrRecMsg); } catch (SocketException) { string str = "网络错误,请退出聊天室"; txtMsg.AppendText("我:" + GetCurrentTime() + "\r\n" + str + "\r\n"); return; } lock (objLock) { //获取传输的数据中数据的位数 for (length = 0; arrRecMsg[length] != '\0' || length > 1024; length++) { } //越界 if (length > 1024) { continue; } byte[] rec = new byte[length]; Array.Clear(rec, 0, length); for (int i = 0; i < length; i++) { rec[i] = arrRecMsg[i]; } msg = PackCodec.Deserialize <commum.Message>(rec); if (msg == null) { continue; } string strRecMsg = Encoding.UTF8.GetString(msg.message, 0, msg.message.Length); string strRecName = Encoding.UTF8.GetString(msg.ipAddress, 0, msg.ipAddress.Length); if (strRecName.Equals("0"))//其他信息 { txtMsg.AppendText(strRecMsg + "\r\n"); } else { txtMsg.AppendText(strRecName + ":" + GetCurrentTime() + "\r\n" + strRecMsg + "\r\n"); } } } }