最初的版本是這樣的:點擊打開鏈接。但一直沒有調好,所以就咨詢了一下同事翔哥,最後初步搞定!
客戶端代碼:
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; } } } }
效果如下:
客戶端可以發送消息給服務端,服務端也可以發送消息給客戶端。
缺點:
現在服務端只能連接一個客戶端