最初的版本是這樣的:點擊開啟連結。但一直沒有調好,所以就諮詢了一下同事翔哥,最後初步搞定!
用戶端代碼:
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;using System.Diagnostics;namespace SocketClient{ public partial class Client : Form { Socket vsServerSocket; Thread vsClientThread; string strIP = "127.0.0.1"; public delegate void PassString(string strMsg); int nPort = 9001; public Client() { InitializeComponent(); } public void SetSendData(string strMsg) { if (tBoxClientSend.InvokeRequired == true) { PassString d = new PassString(SetSendData); this.Invoke(d, new object[] { strMsg }); } else { tBoxClientSend.Text = strMsg; } } public void SetRecvData(string strMsg) { if (tBoxClientReceive.InvokeRequired == true) { PassString d = new PassString(SetRecvData); this.Invoke(d, new object[] { strMsg }); } else { tBoxClientReceive.Text = strMsg; } } private void ClientHandle() { string strRecv = string.Empty; //IPEndPoint其實就是一個IP地址和連接埠的綁定,可以代表一個服務,用來Socket通訊。 //IPAddress類中有一個 Parse()方法,可以把點分的十進位IP表示轉化成IPAddress類 IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(strIP), nPort); //建立通訊端執行個體 //這裡建立的時候用ProtocolType.Tcp,表示建立一個連線導向(TCP)的Socket vsServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { //將所建立的通訊端與IPEndPoint綁定 vsServerSocket.Bind(ipep); } catch (SocketException ex) { MessageBox.Show("Connect Error: " + ex.Message); return; } Byte[] buffer = new Byte[1024]; //設定通訊端為收聽模式 vsServerSocket.Listen(10); //迴圈監聽 while (true) { //接收伺服器資訊 int bufLen = 0; try { Socket vsClientSocket = vsServerSocket.Accept(); bufLen=vsClientSocket.Receive(buffer); vsClientSocket.Send(Encoding.ASCII.GetBytes("aaaaa"), 5, SocketFlags.None); } catch (Exception ex) { MessageBox.Show("Receive Error:" + ex.Message); } strRecv = Encoding.ASCII.GetString(buffer, 0, bufLen); SetRecvData(strRecv); //vsClientSocket.Shutdown(SocketShutdown.Both); //vsClientSocket.Close(); } } //發送資料 private void btnSend_Click(object sender, EventArgs e) { byte[] data = new byte[1024]; string ss = tBoxClientSend.Text; Socket centerClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint GsServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9002); centerClient.Connect(GsServer); centerClient.Send(Encoding.ASCII.GetBytes(ss)); centerClient.Close(); } private void Client_Load(object sender, EventArgs e) { //串連伺服器 //通過ThreadStart委託告訴子線程講執行什麼方法 vsClientThread = new Thread(new ThreadStart(ClientHandle)); vsClientThread.Start(); } //表單關閉時殺死用戶端進程 private void Client_FormClosing(object sender, FormClosingEventArgs e) { KillProcess(); } //殺死用戶端進程 private void KillProcess() { Process[] processes = Process.GetProcessesByName("SocketClient"); foreach (Process process in processes) { process.Kill(); break; } } }}
服務端代碼:
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.Threading;using System.Net.Sockets;using System.Net;using System.Diagnostics;namespace SocketServer{ public partial class Server : Form { Thread vsServerThread; Socket vsServerSocket; string strIP = "127.0.0.1"; public delegate void PassString(string strMsg); int nPort = 9002; public Server() { InitializeComponent(); } private void SeverSendData(string strMsg) { //Control.InvokeRequired 屬性,命名空間: System.Windows.Forms //擷取一個值,該值指示調用方在對控制項進行方法調用時是否必須調用 Invoke 方法,因為調用方位於建立控制項所在的線程以外的線程中。 if (tBoxServerSend.InvokeRequired == true) { //Control.Invoke 方法 (Delegate) //在擁有此控制項的基礎視窗控制代碼的線程上執行指定的委託。 PassString d = new PassString(SeverSendData); this.Invoke(d, new object[] { strMsg }); } else { tBoxServerSend.Text = strMsg; } } private void SeverRecvData(string strMsg) { if (tBoxServerReceive.InvokeRequired == true) { PassString d = new PassString(SeverRecvData); this.Invoke(d, new object[] { strMsg }); } else { tBoxServerReceive.Text = strMsg; } } private void ServerStart() { string strRecv = string.Empty; //建立IPEndPoint執行個體 IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(strIP), nPort); //建立一個通訊端 vsServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //將所建立的通訊端與IPEndPoint綁定 try { vsServerSocket.Bind(ipep); } catch (Exception ee) { MessageBox.Show(ee.ToString()); return; } //設定通訊端為收聽模式 vsServerSocket.Listen(10); int bufLen = 0; //迴圈監聽 while (true) { //在通訊端上接收接入的串連 Socket vsClientSocket = vsServerSocket.Accept(); try { Byte[] buffer = new Byte[1024]; //在通訊端上接收用戶端發送的資訊 bufLen = vsClientSocket.Receive(buffer); vsClientSocket.Send(Encoding.ASCII.GetBytes("aaaaa"), 5, SocketFlags.None); if (bufLen == 0) continue; //將指定位元組數組中的一個位元組序列解碼為一個字串。 strRecv = Encoding.ASCII.GetString(buffer, 0, bufLen); SeverRecvData(strRecv.ToString()); } catch (Exception ex) { MessageBox.Show("Listening Error: " + ex.Message); vsClientSocket.Close(); vsServerSocket.Close(); } } } private void btnSend_Click(object sender, EventArgs e) { byte[] data = new byte[1024]; string ss = tBoxServerSend.Text; Socket centerClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint GsServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9001); centerClient.Connect(GsServer); centerClient.Send(Encoding.ASCII.GetBytes(ss)); centerClient.Send(Encoding.ASCII.GetBytes(ss)); //Thread.Sleep(100); //centerClient.Close(); } private void Server_Load(object sender, EventArgs e) { vsServerThread = new Thread(new ThreadStart(ServerStart)); vsServerThread.Start(); } //表單關閉時殺死用戶端進程 private void Server_FormClosing(object sender, FormClosingEventArgs e) { KillProcess(); } //殺死用戶端進程 private void KillProcess() { Process[] processes = Process.GetProcessesByName("Server"); foreach (Process process in processes) { process.Kill(); break; } } }}
效果如下:
用戶端可以發送訊息給服務端,服務端也可以發送訊息給用戶端。
缺點:
現在服務端只能串連一個用戶端
以上就是C# Socket 線程的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!