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.效果圖

