服务器
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.IO; using System.Net; using System.Threading; namespace 聊天程序 { public partial class Server : Form { private TcpListener myListener; private List<User> userList = new List<User>(); private const int port = 3000; private bool isNormalExit = false; IPAddress localAddress; public Server() { InitializeComponent(); ListboxState.HorizontalScrollbar = true; IPAddress[] addIp = Dns.GetHostAddresses(Dns.GetHostName()); localAddress = addIp[0]; BtnStop.Enabled = false; } private void BtnStart_Click(object sender, EventArgs e) { myListener = new TcpListener(localAddress, port); myListener.Start(); AddItemToListBox(string.Format("开始在{0}:{1}监听客户连接", localAddress, port)); Thread connectThread = new Thread(ListenClient); connectThread.Start(); BtnStop.Enabled = true; BtnStart.Enabled = false; } private void ListenClient() { TcpClient newClient = null; while (true) { try { newClient = myListener.AcceptTcpClient(); } catch { break; } User user = new User(newClient); Thread receiveThread = new Thread(ReceiveData); receiveThread.Start(user); userList.Add(user); AddItemToListBox(string.Format("[{0}]进入", newClient.Client.RemoteEndPoint)); AddItemToListBox(string.Format("当前的在线的用户数:{0}", userList.Count)); } } private void ReceiveData(object userState) { User user = (User)userState; TcpClient tcpClient = user.Clinet; string receiveString = null; while (false == isNormalExit) { try { receiveString = user.Br.ReadString(); } catch { AddItemToListBox(string.Format("与用户{0}失去连接,已终止接收该用户的信息", tcpClient.Client.RemoteEndPoint)); RemoveUser(user); break; } AddItemToListBox(string.Format("来自[{0}]:{1}", user.Clinet.Client.RemoteEndPoint, receiveString)); string[] spliteString = receiveString.Split(','); switch (spliteString[0]) { case "Login": user.UserName = spliteString[1]; SendToAllClient(user, receiveString); break; case "Logout": SendToAllClient(user, receiveString); RemoveUser(user); return ; case "Talk": string talkString = null; talkString = receiveString.Substring(spliteString[0].Length + spliteString[1].Length + 2); AddItemToListBox(string.Format("[{0}]对[{1}]说:{2}", user.UserName, spliteString[1], talkString)); SendToClient(user, "talk," + user.UserName + "," + talkString); foreach (User target in userList) { if (target.UserName == spliteString[1] && user.UserName != spliteString[1]) { SendToClient(target, "talk," + user.UserName + "," + talkString); break; } } break; default: AddItemToListBox(string.Format("什么意思啊:" + receiveString)); break; } } } private void SendToAllClient(User user, string message) { string command = message.Split(',')[0].ToLower(); if ("login" == command) { for (int i = 0; i < userList.Count; i++) { //向其他用户发送该用法登录信息 SendToClient(userList[i], message); //向该用户发送其他用户登录信息 if (userList[i].UserName != user.UserName) { SendToClient(user, "login," + userList[i].UserName); } } } if ("logout" == command) { for (int i = 0; i < userList.Count; i++) { //向其他用户发送该用户退出信息 if (userList[i].UserName != user.UserName) { SendToClient(userList[i], message); } } } } private void SendToClient(User user, string message) { try { user.Bw.Write(message); user.Bw.Flush(); AddItemToListBox(string.Format("向[{0}]发送信息:{1}", user.UserName, message)); } catch { AddItemToListBox(string.Format("向[{0}]发送信息失败!")); } } private delegate void AddItemToListBoxDelegate(string str); private void AddItemToListBox(string str) { if (ListboxState.InvokeRequired) { AddItemToListBoxDelegate d = AddItemToListBox; ListboxState.Invoke(d, str); } else { ListboxState.Items.Add(str); ListboxState.SelectedIndex = ListboxState.Items.Count - 1; ListboxState.ClearSelected(); } } private void RemoveUser(User user) { userList.Remove(user); user.Close(); AddItemToListBox(string.Format("当前在线用户数:{0}", userList.Count)); } private void BtnStop_Click(object sender, EventArgs e) { AddItemToListBox("开始停止服务,用户依次退出"); isNormalExit = true; for (int i = 0; i < userList.Count; i++) { RemoveUser(userList[i]); } myListener.Stop(); BtnStart.Enabled = true; BtnStop.Enabled = false; } private void Server_FormClosing(object sender, FormClosingEventArgs e) { if (myListener != null) { BtnStop.PerformClick(); } } } }
?
?
User类
?
using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.IO; namespace 聊天程序 { public class User { private TcpClient client; private BinaryReader br; private BinaryWriter bw; private string userName; public TcpClient Clinet { get { return client; } } public BinaryReader Br { get { return br; } } public BinaryWriter Bw { get { return bw; } } public string UserName { get { return userName; } set {userName=value;} } public User (TcpClient clinet) { this.client = clinet; NetworkStream networkStream = clinet.GetStream(); br = new BinaryReader(networkStream); bw = new BinaryWriter(networkStream); } public void Close() { br.Close(); bw.Close(); client.Close(); } } }
?
?
客户端
?
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; namespace Client { public partial class Client : Form { private bool isExit = false; private TcpClient tcpClient; private BinaryReader br; private BinaryWriter bw; public Client() { InitializeComponent(); listBoxMessage.HorizontalScrollbar = true; listBoxUser.HorizontalScrollbar = true; Random r = new Random((int)DateTime.Now.Ticks); txtUser.Text = "user" + r.Next(100, 999); btnSend.Enabled = false; } private void btnLogin_Click(object sender, EventArgs e) { btnLogin.Enabled = false; try { tcpClient = new TcpClient("192.168.14.56", 3000); AddMessage("连接成功"); btnSend.Enabled = true; } catch { btnLogin.Enabled = true; AddMessage("连接失败!"); return; } NetworkStream networkStream = tcpClient.GetStream(); br = new BinaryReader(networkStream); bw = new BinaryWriter(networkStream); SendMessage("Login," + txtUser.Text + ""); Thread receiveThread = new Thread(ReceiveData); receiveThread.IsBackground = true; receiveThread.Start(); } private void ReceiveData() { string receiveString = null; while (false == isExit) { try { receiveString = br.ReadString(); } catch { AddMessage("与服务器失去连接!"); break; } string[] splitString = receiveString.Split(','); string command = splitString[0].ToLower(); switch (command) { case "login": AddUser(splitString[1]); break; case "logout": RemoveUser(splitString[1]); break; case "talk": AddMessage(splitString[1] + ":"); AddMessage(receiveString.Substring(splitString[0].Length + splitString[1].Length + 2)); break; default: AddMessage("什么意思啊" + receiveString); break; } } Application.Exit(); } private void SendMessage(string message) { try { bw.Write(message); bw.Flush(); } catch { AddMessage("发送信息失败!"); } } private delegate void AddMessageDelegate(string str); private void AddMessage(string str) { if (listBoxMessage.InvokeRequired) { AddMessageDelegate d = AddMessage; listBoxMessage.Invoke(d, str); } else { listBoxMessage.Items.Add(str); listBoxMessage.SelectedIndex = listBoxMessage.Items.Count - 1; listBoxMessage.ClearSelected(); } } private delegate void AddUserDelegate(string str); private void AddUser(string str) { if (listBoxUser.InvokeRequired) { AddUserDelegate d = AddUser; listBoxUser.Invoke(d, str); } else { listBoxUser.Items.Add (str); listBoxUser.SelectedIndex = listBoxMessage.Items.Count - 1; listBoxUser.ClearSelected(); } } private delegate void RemoveUserDelegate(string str); private void RemoveUser(string str) { if (listBoxUser.InvokeRequired) { RemoveUserDelegate d = RemoveUser; listBoxUser.Invoke(d, str); } else { listBoxUser.Items.Remove(str); listBoxUser.SelectedIndex = listBoxMessage.Items.Count - 1; listBoxUser.ClearSelected(); } } private void txtMessage_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Return) { btnSend.PerformClick(); } } private void btnSend_Click(object sender, EventArgs e) { if (listBoxUser.SelectedIndex != -1) { SendMessage("Talk," + listBoxUser.SelectedItem.ToString() + "," + txtMessage.Text); txtMessage.Clear(); } else { MessageBox.Show("请选择接收的用户"); } } private void Client_FormClosing(object sender, FormClosingEventArgs e) { if (null != tcpClient) { SendMessage("Logout," + txtUser.Text); isExit = true; br.Close(); bw.Close(); tcpClient.Close(); } } } }
?
?
?
?
?
?