C#Socket通信
概述
所謂套接字(Socket),就是對網絡中不同主機上的應用進程之間進行雙向通信的端點的抽象。一個套接字就是網絡上進程通信的一端,提供了應用層進程利用網絡協議交換數據的機制。從所處的地位來講,套接字上聯應用進程,下聯網絡協議棧,是應用程序通過網絡協議進行通信的接口,是應用程序與網絡協議根進行交互的接口。
套接字是通信的基石,是支持TCP/IP協議的路通信的基本操作單元。可以將套接字看作不同主機間的進程進行雙間通信的端點,它構成了單個主機內及整個網絡間的編程界面。套接字存在于通信域中,通信域是為了處理一般的線程通過套接字通信而引進的一種抽象概念。套接字通常和同一個域中的套接字交換數據(數據交換也可能穿越域的界限,但這時一定要執行某種解釋程序),各種進程使用這個相同的域互相之間用Internet協議簇來進行通信。
Socket(套接字)可以看成是兩個網絡應用程序進行通信時,各自通信連接中的端點,這是一個邏輯上的概念。它是網絡環境中進程間通信的API(應用程序編程接口),也是可以被命名和尋址的通信端點,使用中的每一個套接字都有其類型和一個與之相連進程。通信時其中一個網絡應用程序將要傳輸的一段信息寫入它所在主機的 Socket中,該 Socket通過與網絡接口卡(NIC)相連的傳輸介質將這段信息送到另外一臺主機的 Socket中,使對方能夠接收到這段信息。Socket是由IP地址和端口結合的,提供向應用層進程傳送數據包的機制。
服務端
using?System; using?System.Collections.Generic; using?System.ComponentModel; using?System.Data; using?System.Drawing; using?System.Linq; using?System.Net; using?System.Net.Sockets; using?System.Text; using?System.Threading; using?System.Windows.Forms;namespace?SocketForm {public?partial?class?Form1?:?Form{public?Form1(){InitializeComponent();}private?void?bt_connnect_Click(object?sender,?EventArgs?e){try{//點擊開始監聽時?在服務端創建一個負責監聽IP和端口號的SocketSocket?socketWatch?=?new?Socket(AddressFamily.InterNetwork,?SocketType.Stream,?ProtocolType.Tcp);IPAddress?ip?=?IPAddress.Any;//創建對象端口IPEndPoint?point?=?new?IPEndPoint(ip,?Convert.ToInt32(tb_port.Text));socketWatch.Bind(point);//綁定端口號ShowMsg("監聽成功!");socketWatch.Listen(10);//設置監聽//創建監聽線程Thread?thread?=?new?Thread(Listen);thread.IsBackground?=?true;thread.Start(socketWatch);}catch?{?}}///?<summary>///?等待客戶端的連接?并且創建與之通信的Socket///?</summary>Socket?socketSend;void?Listen(object?o){try{Socket?socketWatch?=?o?as?Socket;while?(true){socketSend?=?socketWatch.Accept();//等待接收客戶端連接ShowMsg(socketSend.RemoteEndPoint.ToString()?+?":"?+?"連接成功!");//開啟一個新線程,執行接收消息方法Thread?r_thread?=?new?Thread(Received);r_thread.IsBackground?=?true;r_thread.Start(socketSend);}}catch?{?}}///?<summary>///?服務器端不停的接收客戶端發來的消息///?</summary>///?<param?name="o"></param>void?Received(object?o){try{Socket?socketSend?=?o?as?Socket;while?(true){//客戶端連接服務器成功后,服務器接收客戶端發送的消息byte[]?buffer?=?new?byte[1024?*?1024?*?3];//實際接收到的有效字節數int?len?=?socketSend.Receive(buffer);if?(len?==?0){break;}string?str?=?Encoding.UTF8.GetString(buffer,?0,?len);ShowMsg(socketSend.RemoteEndPoint?+?":"?+?str);}}catch?{?}}///?<summary>///?服務器向客戶端發送消息///?</summary>///?<param?name="str"></param>void?Send(string?str)?{byte[]?buffer?=?Encoding.UTF8.GetBytes(str);socketSend.Send(buffer);}void?ShowMsg(string?msg){listBox1.Items.Add(msg?+?"\r\n");}private?void?Form1_Load(object?sender,?EventArgs?e){Control.CheckForIllegalCrossThreadCalls?=?false;}private?void?bt_send_Click(object?sender,?EventArgs?e){Send(txt_msg.Text.Trim());}} }客戶端
using?System; using?System.Collections.Generic; using?System.ComponentModel; using?System.Data; using?System.Drawing; using?System.Linq; using?System.Net; using?System.Net.Sockets; using?System.Text; using?System.Threading; using?System.Windows.Forms;namespace?SocketClient {public?partial?class?Form1?:?Form{public?Form1(){InitializeComponent();}Socket?socketSend;private?void?bt_connect_Click(object?sender,?EventArgs?e){try{//創建客戶端Socket,獲得遠程ip和端口號socketSend?=?new?Socket(AddressFamily.InterNetwork,?SocketType.Stream,?ProtocolType.Tcp);IPAddress?ip?=?IPAddress.Parse(txt_ip.Text);IPEndPoint?point?=?new?IPEndPoint(ip,?Convert.ToInt32(txt_port.Text));socketSend.Connect(point);ShowMsg("連接成功!");//開啟新的線程,不停的接收服務器發來的消息Thread?c_thread?=?new?Thread(Received);c_thread.IsBackground?=?true;c_thread.Start();}catch?(Exception){ShowMsg("IP或者端口號錯誤...");}}void?ShowMsg(string?str){textBox1.AppendText(str?+?"\r\n");}///?<summary>///?接收服務端返回的消息///?</summary>void?Received(){while?(true){try{byte[]?buffer?=?new?byte[1024?*?1024?*?3];//實際接收到的有效字節數int?len?=?socketSend.Receive(buffer);if?(len?==?0){break;}string?str?=?Encoding.UTF8.GetString(buffer,?0,?len);ShowMsg(socketSend.RemoteEndPoint?+?":"?+?str);}catch?{?}}}///?<summary>///?向服務器發送消息///?</summary>///?<param?name="sender"></param>///?<param?name="e"></param>private?void?bt_send_Click(object?sender,?EventArgs?e){try{string?msg?=?txt_msg.Text.Trim();byte[]?buffer?=?new?byte[1024?*?1024?*?3];buffer?=?Encoding.UTF8.GetBytes(msg);socketSend.Send(buffer);}catch?{?}}private?void?Form1_Load(object?sender,?EventArgs?e){Control.CheckForIllegalCrossThreadCalls?=?false;}} }總結
以上是生活随笔為你收集整理的C#Socket通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端快闪三:多环境灵活配置react
- 下一篇: 批量生成 Gitee 仓库克隆命令的方法