C#上位機之—WinForm實現Socket異步通信示例

工做中經常使用到的一些知識點,老是用完就忘,第一次嘗試用博客記錄下來,以備後用;服務器

Socket通信,Socket(套接字)是基於TCP/IP通信方式的封裝好的類,調用時須要添加下面的服務引用:網絡

.......
10 using System.Net; 11 using System.Net.Sockets;

窗體頁面搭建,上面爲服務器區,下面爲客戶端區:ide

創建兩個類,一個表示服務器,一個表示客戶端,函數

首先創建服務器類:測試

1.聲明變量:IP地址,端口號,EndPoint,Socket類,數據Buffer等this

 1         string ip;//IP地址
 2         string port;//端口號
 3         IPEndPoint endPoint;//網絡端點
 4         Socket socServer;//偵聽鏈接套接字
 5         Socket socClient;//通信套接字
 6         byte[] dataReceived = new byte[50000];  7 
 8         public delegate void delegateDisplayMsg(string type,string msg);  9         public delegateDisplayMsg OnDisplay; 10 
11         public SocketServer() 12  { 13             socServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 14         }
View Code

 

2.偵聽鏈接函數:spa

public void StartListen(string ip,string port) { this.ip = ip; this.port = port; endPoint = new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(port)); socServer.Bind(endPoint); socServer.Listen(0); socServer.BeginAccept(new AsyncCallback(OnClientConnect), null); ShowMsg("Wait Connect"); }
View Code

3.接受數據函數:code

public void OnClientConnect(IAsyncResult asyn) { socClient = socServer.EndAccept(asyn); WaitForData(); ShowMsg("Client Connected " + socClient.RemoteEndPoint.ToString()); } public void WaitForData() { if (socClient != null) socClient.BeginReceive(dataReceived, 0, dataReceived.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null); } public void OnDataReceived(IAsyncResult asyn) { int dataLength = socClient.EndReceive(asyn); byte[] chars = new byte[dataLength]; Buffer.BlockCopy(dataReceived, 0, chars, 0, dataLength); string msg = Encoding.ASCII.GetString(chars); ShowMsg("<=" + msg); WaitForData(); }
View Code

4.發送數據函數:server

public void SendMsg(string msg) { byte[] data = Encoding.Default.GetBytes(msg); socClient.Send(data); ShowMsg("=>" + msg); }
View Code

而後創建客戶端類:blog

1.聲明變量

string ip;//IP地址
        string port;//端口號
        IPEndPoint endPoint;//網絡端點
        Socket socClient;//通信套接字
        byte[] dataReceived = new byte[50000];//數據Buffer

        public delegate void delegateDisplayMsg(string type,string msg); public delegateDisplayMsg OnDisplay; public SocketClient() { socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); }
View Code

2.鏈接服務器函數:

public void Connect(string ip, string port) { this.ip = ip; this.port = port; endPoint = new IPEndPoint(IPAddress.Parse(this.ip), int.Parse(port)); socClient.BeginConnect(endPoint, new AsyncCallback(OnToConnected), null); }
View Code

3.接受數據函數:

public void OnToConnected(IAsyncResult asyn) { socClient.EndConnect(asyn); WaitForData(); ShowMsg("Connect Success"); } public void WaitForData() { if (socClient != null) socClient.BeginReceive(dataReceived, 0, dataReceived.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null); } public void OnDataReceived(IAsyncResult asyn) { int dataLenth = socClient.EndReceive(asyn); byte[] chars = new byte[dataLenth]; Buffer.BlockCopy(dataReceived, 0, chars, 0, dataLenth); string msg = Encoding.ASCII.GetString(chars); ShowMsg("<=" + msg); WaitForData(); }
View Code

4.發送數據函數:

public void SendMsg(string msg) { byte[] data = Encoding.Default.GetBytes(msg); socClient.Send(data); ShowMsg("=>" + msg); }
View Code

服務器類與客戶端類,已經創建完成,下面對兩個類進行實例化,並Link窗體控件的事件函數,以下:

1.實例化:

public void Init() { Server = new SocketServer(); Client = new SocketClient(); Server.OnDisplay += ShowMsg; Client.OnDisplay += ShowMsg; }

2.按鈕點擊事件:

private void btn_StartListen_Click(object sender, EventArgs e) { Server.StartListen(txt_serverIP.Text.ToString(), txt_serverPort.Text.ToString()); btn_StartListen.BackColor = Color.LimeGreen; } private void btn_Connect_Click(object sender, EventArgs e) { Client.Connect(txt_clientIP.Text.ToString(), txt_clientPort.Text.ToString()); } private void btn_serverSend_Click(object sender, EventArgs e) { Button b = (Button)sender; bool isServer = b.Name.Contains("server"); if (isServer) Server.SendMsg(txt_serverMsg.Text.ToString()); else Client.SendMsg(txt_clientMsg.Text.ToString()); }
View Code

如今啓動程序,測試發送接收功能是否正常

至此,一個簡單的Socket通信模型已經完成,實際應用中還需考慮通信異常,通信協議,多個客戶端通信等事項,第一次寫博,歡迎你們多多指正;

相關文章
相關標籤/搜索