Socket实现简单的聊天通信
最近学习了Socket后,感觉Socket挺好玩的,在博客中看到socket在实时聊天功能的很强大,于是乎就做了一个简单的聊天功能,今天贴出来,能够与大家一起共享,有不对之处,能够给予指出,谢谢!
服务器中的代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Threading; using System.Net; namespace Chat_SocketServer { public partial class Form1 : Form { public Form1() { InitializeComponent(); TextBox.CheckForIllegalCrossThreadCalls = false; } //服务端 监听套接字 Socket socketWatch = null; //服务端 监听线程 Thread threadWatch = null; //字典集合:保存通信套接字 Dictionary<string,Socket> dictCon = new Dictionary<string,Socket>(); private void Watch_Click(object sender, EventArgs e) { try { //1.创建监听套接字 使用 ip4协议,流式传输,TCP连接 socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2.绑定端口 //2.1获取网络节点对象 IPAddress address = IPAddress.Parse(ip_txt.Text); IPEndPoint endPoint = new IPEndPoint(address, int.Parse(port_txt.Text)); //2.2绑定端口(其实内部 就向系统的 端口表中 注册 了一个端口,并指定了当前程序句柄) socketWatch.Bind(endPoint); //2.3设置监听队列 socketWatch.Listen(10); //2.4开始监听,调用监听线程 执行 监听套接字的 监听方法 threadWatch = new Thread(WatchConnecting); threadWatch.IsBackground = true; threadWatch.Start(); ShowMsg("服务器成功启动啦!"); } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } private void Send_Click(object sender, EventArgs e) { string strClient = this.lbOnline.Text; if (string.IsNullOrEmpty(strClient)) { MessageBox.Show("请选择你要发送消息的客户端!"); return; } if (dictCon.ContainsKey(strClient)) { string strMsg = this.send_txt.Text.Trim(); ShowMsg("\r\n向客户端【" + strClient + "】说:" + strMsg); //使用 指定的 通信套接字 将 字符串 发送到 指定的客户端 byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg); dictCon[strClient].Send(arrMsg); } this.send_txt.Text = ""; } void WatchConnecting() { //2.4开始监听:此方法会阻断当前线程,直到有 其它程序 连接过来,才执行完毕 Socket sokMsg = socketWatch.Accept(); //将当前连接成功的 【与客户端通信的套接字】 的 标识 保存起来,并显示到 列表中 //将 远程客户端的 ip和端口 字符串 存入 列表 this.lbOnline.Items.Add(sokMsg.RemoteEndPoint.ToString()); //将 服务端的通信套接字 存入 字典集合 dictCon.Add(sokMsg.RemoteEndPoint.ToString(), sokMsg); ShowMsg("\r\n客户端【" + sokMsg.RemoteEndPoint.ToString() + "】上线了!"); //2.5创建 通信线程 Thread thrMsg = new Thread(ReceiveMsg); thrMsg.IsBackground = true; thrMsg.Start(sokMsg); } void ReceiveMsg(object obj) { try { Socket sokMsg = obj as Socket; //3.通信套接字 监听 客户端的 消息 //3.1创建 消息缓存区 byte[] arrMsg = new byte[1024 * 1024 * 1]; while (true) { //3.2接收客户端的消息 并存入 缓存区,注意:Receive方法也会阻断当前的线程 sokMsg.Receive(arrMsg); //3.3将接收到的消息 转成 字符串 string strMsg = System.Text.Encoding.UTF8.GetString(arrMsg); //3.4将消息 显示到 文本框 ShowMsg("\r\n" + strMsg); } } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } void ShowMsg(string strmsg) { this.show_txt.AppendText(strmsg + "\r\n"); } } }
客户端的代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Threading; using System.Net; namespace Chat_SocketClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); TextBox.CheckForIllegalCrossThreadCalls = false; } //客户端 通信套接字 Socket socketMsg = null; //客户端 通信线程 Thread threadMsg = null; //标记任务 bool isRec = true; private void Conn_Click(object sender, EventArgs e) { try { //1.创建监听套接字 使用 ip4协议,流式传输,TCP连接 socketMsg = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //2.获取要连接的服务端 节点 //2.1获取网络节点对象 IPAddress address = IPAddress.Parse(ip_textbox.Text); IPEndPoint endPoint = new IPEndPoint(address, int.Parse(port_textbox.Text)); //3.向服务端 发送链接请求 socketMsg.Connect(endPoint); ShowMsg("连接服务器成功~~!"); //4.开启通信线程 threadMsg = new Thread(RecevieMsg); threadMsg.IsBackground = true; threadMsg.Start(); } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } private void Send_Click(object sender, EventArgs e) { string strMsg = this.info_textbox.Text.Trim(); byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg); ShowMsg("\r\n我说:" + strMsg); socketMsg.Send(arrMsg); this.info_textbox.Text = ""; } void RecevieMsg() { try { //3.1创建 消息缓存区 byte[] arrMsg = new byte[1024 * 1024 * 1]; while (isRec) { socketMsg.Receive(arrMsg); string strMsg = System.Text.Encoding.UTF8.GetString(arrMsg); ShowMsg("\r\n服务器说:" + strMsg); } } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } void ShowMsg(string strmsg) { this.richTextBox1.AppendText(strmsg + "\r\n"); } } }
相关资料推荐:http://www.newxing.com/Tech/DotNet/CSharp/Socket_133.html写的聊天通信也很不错哟!
版权声明:本文为ysq0908原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。