1 using System; 2 using System.Windows.Forms; 3 //添加的命名空间引用 4 using System.Net; 5 using System.Net.Sockets; 6 using System.Threading; 7 using System.IO; 8 namespace SyncChatClient 9 { 10 public partial class MainForm : Form 11 { 12 private bool isExit = false; 13 private TcpClient client; 14 private BinaryReader br; 15 private BinaryWriter bw; 16 public MainForm() 17 { 18 InitializeComponent(); 19 Random r = new Random((int)DateTime.Now.Ticks);//?????????????????????????????????????? 20 textBoxUserName.Text = "user" + r.Next(100, 999);//????????????????????????????????????? 21 listBoxOnlineStatus.HorizontalScrollbar = true;//??????????????????????????????????????????????????????????????????????????? 22 23 } 24 /// <summary> 25 /// 【连接服务器】按钮的Click事件 26 /// </summary> 27 private void buttonConnect_Click(object sender, EventArgs e) 28 { 29 buttonConnect.Enabled = false; 30 try 31 { 32 //此处为方便演示,实际使用时要将Dns.GetHostName()改为服务器域名 33 client = new TcpClient(Dns.GetHostName(), 51888); 34 //后面添加的函数,给文本框中添加信息 35 AddTalkMessage("连接成功"); 36 } 37 catch 38 { 39 AddTalkMessage("连接失败"); 40 buttonConnect.Enabled = true; 41 return; 42 } 43 //获取网络流 44 NetworkStream networkStream = client.GetStream(); 45 //将网络流作为二进制读写对象 46 br = new BinaryReader(networkStream); 47 bw = new BinaryWriter(networkStream); 48 //向服务器端发送信息 49 SendMessage("Login," + textBoxUserName.Text); 50 Thread threadReceive = new Thread(new ThreadStart(ReceiveData));//??????????????????????????????????????????????????????? 51 threadReceive.IsBackground = true;//??????????????????????????????????????????????????????????????????????????? 52 threadReceive.Start(); 53 } 54 /// <summary>处理接收的服务器端数据</summary> 55 private void ReceiveData() 56 { 57 string receiveString = null; 58 while (isExit == false) 59 { 60 try 61 { 62 //从网络流中读出字符串 63 //此方法会自动判断字符串长度前缀,并根据长度前缀读出字符串 64 receiveString = br.ReadString(); 65 } 66 catch 67 { 68 if (isExit == false) 69 { 70 MessageBox.Show("与服务器失去联系。"); 71 } 72 break; 73 } 74 string[] splitString= receiveString.Split(‘,‘); 75 string command = splitString[0].ToLower(); 76 switch (command) 77 { 78 case "login": //格式:login,用户名 79 AddOnline(splitString[1]);//在listBoxOnlineStatus当中添加已经登陆的用户的信息 80 break; 81 case "logout": //格式:logout,用户名 82 RemoveUserName(splitString[1]);//移除listBoxOnlineStatus当中已经离线的信息 83 break; 84 case "talk": //格式:talk,用户名,对话信息 85 //AddTalkMessage(splitString[1] + ":\r\n"); 86 //AddTalkMessage(receiveString.Substring( 87 // splitString[0].Length + splitString[1].Length+2)); 88 AddTalkMessage(string.Format("[{0}]说:{1}", 89 splitString[1],receiveString.Substring( 90 splitString[0].Length + splitString[1].Length + 2))); 91 break; 92 default: 93 AddTalkMessage("什么意思啊:" + receiveString); 94 break; 95 } 96 } 97 Application.Exit(); 98 } 99 /// <summary>向服务器端发送信息</summary> 100 private void SendMessage(string message) 101 { 102 try 103 { 104 //将字符串写入网络流,此方法会自动附加字符串长度前缀 105 bw.Write(message); 106 bw.Flush(); 107 } 108 catch 109 { 110 AddTalkMessage("发送失败!"); 111 } 112 } 113 /// <summary>【发送】按钮的Click事件</summary> 114 private void buttonSend_Click(object sender, EventArgs e) 115 { 116 if (listBoxOnlineStatus.SelectedIndex != -1) 117 { 118 //SendMessage("Talk," + listBoxOnlineStatus.SelectedItem + "," + textBoxSend.Text+"\r\n"); 119 SendMessage("Talk," + listBoxOnlineStatus.SelectedItem + "," + textBoxSend.Text); 120 textBoxSend.Clear(); 121 } 122 else 123 { 124 MessageBox.Show("请先在[当前在线]中选择一个对话者"); 125 } 126 } 127 /// <summary>关闭窗口时触发的事件</summary> 128 private void MainForm_FormClosing(object sender, FormClosingEventArgs e) 129 { 130 //未与服务器连接前client为null 131 if (client != null) 132 { 133 SendMessage("Logout," + textBoxUserName.Text); 134 isExit = true; 135 br.Close(); 136 bw.Close(); 137 client.Close(); 138 } 139 } 140 /// <summary>在发送信息文本框中按下【Enter】键触发的事件</summary> 141 private void textBoxSend_KeyPress(object sender, KeyPressEventArgs e) 142 { 143 if (e.KeyChar == (char)Keys.Return) 144 { 145 //触发buttonSend的Click事件 146 buttonSend.PerformClick(); 147 } 148 } 149 private delegate void MessageDelegate(string message); 150 /// <summary> 在richTextBoxTalkInfo中追加聊天信息</summary> 151 private void AddTalkMessage(string message) 152 { 153 if (richTextBoxTalkInfo.InvokeRequired) 154 { 155 MessageDelegate d = new MessageDelegate(AddTalkMessage); 156 richTextBoxTalkInfo.Invoke(d, new object[] { message });//????????????????????????????????????????????? 157 } 158 else 159 { 160 richTextBoxTalkInfo.AppendText(message + Environment.NewLine); 161 richTextBoxTalkInfo.ScrollToCaret(); 162 } 163 } 164 private delegate void AddOnlineDelegate(string message); 165 /// <summary> 在listBoxOnlineStatus中添加在线的其它客户端信息</summary> 166 private void AddOnline(string userName) 167 { 168 if (listBoxOnlineStatus.InvokeRequired) 169 { 170 AddOnlineDelegate d = new AddOnlineDelegate(AddOnline); 171 listBoxOnlineStatus.Invoke(d, new object[] { userName }); 172 } 173 else 174 { 175 listBoxOnlineStatus.Items.Add(userName); 176 listBoxOnlineStatus.SelectedIndex = listBoxOnlineStatus.Items.Count - 1; 177 listBoxOnlineStatus.ClearSelected(); 178 } 179 } 180 private delegate void RemoveUserNameDelegate(string userName); 181 /// <summary> 在listBoxOnlineStatus中移除不在线的其它客户端信息</summary> 182 private void RemoveUserName(string userName) 183 { 184 if (listBoxOnlineStatus.InvokeRequired) 185 { 186 RemoveUserNameDelegate d = RemoveUserName; 187 listBoxOnlineStatus.Invoke(d, userName); 188 } 189 else 190 { 191 listBoxOnlineStatus.Items.Remove(userName); 192 listBoxOnlineStatus.SelectedIndex = listBoxOnlineStatus.Items.Count - 1; 193 listBoxOnlineStatus.ClearSelected(); 194 } 195 } 196 } 197 }
时间: 2024-11-02 21:04:01