-
TCP/IP以及Socket聊天室带类库源码分享
TCP/IP以及Socket聊天室带类库源码分享
最近遇到个设备,需要去和客户的软件做一个网络通信交互,一般的我们的上位机都是作为客户端来和设备通信的,这次要作为服务端来监听客户端,在这个背景下,我查阅了一些大佬们的博客,和一些资料。将这些汇总做了一个简单的服务端监听和客户端的类库,希望对大家有一定的作用,当然更多还是给自己做一个日记。下面是类库和对类库测试的一些全部源代码。
1.通信类库

using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; namespace TCP_DLL { public class PSS_Server { private Dictionary<string, Socket> cilentList = new Dictionary<string, Socket>(); private Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); private Socket ConnCilent; /// <summary> /// 创建服务端 /// </summary> /// <param name="ip">IP地址</param> /// <param name="Port">端口</param> public PSS_Server(string ip, int Port) { IPAddress _IP = IPAddress.Parse(ip); IPEndPoint endPoint = new IPEndPoint(_IP, Port); server.Bind(endPoint); server.Listen(20); } /// <summary> /// 接受客户端的连入请求 /// </summary> /// <param name="retn"></param> /// <returns></returns> public bool Accept(ref string retn) { string info = ""; try { ConnCilent = server.Accept();//接受一个连入的客户端 if (ConnCilent != null) { info = ConnCilent.RemoteEndPoint.ToString(); cilentList.Add(info, ConnCilent); retn = info + "接入服务成功!"; } return true; } catch (Exception) { retn = info + "接入服务失败!"; return false; } } /// <summary> /// 发送消息 /// </summary> /// <param name="str"></param> /// <returns></returns> public bool SendMsg(string str) { try { foreach (var item in cilentList) { byte[] arrMsg = Encoding.UTF8.GetBytes(str); item.Value.Send(arrMsg); } return true; } catch (Exception) { return false; } } /// <summary> /// 接收客户端消息 /// </summary> /// <param name="obj"></param> /// <returns></returns> public bool Receive(object obj, ref string msg) { Socket ConnCilent1 = ConnCilent; IPEndPoint endPoint = null; try { byte[] arrMsg = new byte[1024 * 1024]; int Len = ConnCilent1.Receive(arrMsg); if (Len != 0) { msg = Encoding.UTF8.GetString(arrMsg, 0, Len); endPoint = ConnCilent1.RemoteEndPoint as IPEndPoint; } return true; } catch (Exception) { if (endPoint!=null) { cilentList.Remove(endPoint.ToString()); } return false; } } /// <summary> /// 关闭连接 /// </summary> public void Close() { try { server.Close(); cilentList.Clear(); } catch (Exception) { } } } public class PSS_Cilent { private Socket cilent = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); /// <summary> /// 创建客户端 /// </summary> /// <param name="ip"></param> /// <param name="Port"></param> public bool Connect(string ip, int Port) { IPAddress _ip = IPAddress.Parse(ip); IPEndPoint endPoint = new IPEndPoint(_ip, Port); try { cilent.Connect(endPoint); return true; } catch (Exception) { return false; } } /// <summary> /// 关闭连接 /// </summary> public void Close() { try { cilent.Close(); } catch (Exception) { } } /// <summary> /// 接收消息 /// </summary> /// <param name="o"></param> /// <returns></returns> public bool ReceiveMsg(ref string msg) { Socket _Cilent = cilent; try { //定义客户端收到的信息大小 byte[] arrlist = new byte[1024 * 1024]; //接收到的信息大小 int Len = cilent.Receive(arrlist); msg = Encoding.UTF8.GetString(arrlist, 0, Len); return true; } catch (Exception) { _Cilent.Close(); return false; } } /// <summary> /// 发送消息 /// </summary> /// <param name="msg"></param> /// <returns></returns> public bool SenMsg(string msg) { try { byte[] arrmsg = Encoding.UTF8.GetBytes(msg); cilent.Send(arrmsg); return true; } catch (Exception) { return false; } } } }
2.服务端源代码和界面

using System; using System.Threading.Tasks; using System.Windows.Forms; namespace ServerTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private TCP_DLL.PSS_Server Server; private void textBox3_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (Server.SendMsg(textBox3.Text).Equals(false)) { MessageBox.Show("发送消息失败!!"); return; } textBox3.Clear(); } } private void button1_Click(object sender, EventArgs e) { string retn = ""; Server = new TCP_DLL.PSS_Server(textBox1.Text, int.Parse(textBox2.Text)); textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + "创建服务完成,等待接入..." + "\r\n"))); if (Server.Accept(ref retn).Equals(false)) { MessageBox.Show(retn); return; } textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n"))); Task.Factory.StartNew(() => { while (true) { string retn1 = ""; if (Server.Receive(ref retn).Equals(false)) { MessageBox.Show("接收消息异常!!"); return; } textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n"))); } }); } private void button2_Click(object sender, EventArgs e) { Server.Close(); } } }
2.客户端界面和源代码

using System; using System.Threading.Tasks; using System.Windows.Forms; namespace CilentTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private TCP_DLL.PSS_Cilent Cilent = new TCP_DLL.PSS_Cilent(); private void textBox3_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode==Keys.Enter) { if (Cilent.SenMsg(textBox3.Text).Equals(false)) { MessageBox.Show("发送消息失败!!!"); return; } textBox3.Clear(); } } private void button1_Click(object sender, EventArgs e) { if (Cilent.Connect(textBox1.Text,int.Parse(textBox2.Text)).Equals(false)) { MessageBox.Show("连接失败!!!"); return; } textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + "创建连接完成....." + "\r\n"))); Task.Factory.StartNew(() => { while (true) { string retn = ""; if (Cilent.ReceiveMsg(ref retn).Equals(false)) { MessageBox.Show("接收消息异常!!"); return; } textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n"))); } }); } private void button2_Click(object sender, EventArgs e) { Cilent.Close(); } } }
3.效果图
出处:https://www.cnblogs.com/Tian-HW/p/15224125.html
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
SQL Server -- 解决存储过程传入参数作为s
关于JS定时器的整理
JS中使用Promise.all控制所有的异步请求都完
js中字符串的方法
import-local执行流程与node模块路径解析流程
检测数据类型的四种方法
js中数组的方法,32种方法
前端操作方法
数据类型
window.localStorage.setItem 和 localStorage.setIte
如何完美解决前端数字计算精度丢失与数