1,首先添加兩個windows窗體項目,一個做爲服務端server,一個做爲客戶端Clientwindows
2,而後添加服務端代碼,添加命名空間,界面上添加TextBox控件異步
using System.Net; using System.Net.Sockets;
3,FormLoad方法添加代碼socket
private void Form1_Load(object sender, EventArgs e) { IPEndPoint epServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7878);//IP地址和端口號 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//定義socket socket.Bind(epServer);//綁定 socket.Listen(10);//監聽 socket.BeginAccept(new AsyncCallback(RecVing), socket);//異步接收,回調方法爲RecVing }
4,添加回調方法代碼測試
private void RecVing(IAsyncResult rec_socket) { string cmdstr = ""; Socket sc = (Socket)rec_socket.AsyncState; Socket socket = sc.EndAccept(rec_socket); byte[] bytes = new byte[1024]; int i = socket.Receive(bytes); cmdstr = Encoding.UTF8.GetString(bytes, 0, i); showstrs(cmdstr); sc.BeginAccept(new AsyncCallback(RecVing), sc); }
5,添加showstrs方法,ui
定義委託private delegate void shixudong_invoke(string invokefun);this
private void showstrs(string recv_strs) { if (recv_strs.Length != 0) { if (this.InvokeRequired) { shixudong_invoke invoke = new shixudong_invoke(showstrs); this.Invoke(invoke, (object)recv_strs); } else { textBox1.Text = recv_strs; } } }
6,到此爲止,服務端已經添加完畢spa
7,客戶端代碼,首先跟服務端同樣,添加命名空間,在界面上添加button事件.net
private void button1_Click(object sender, EventArgs e) { IPEndPoint IPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7878);//IP,端口號 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.BeginConnect(IPEndPoint, new AsyncCallback(Sending), socket);//回調方法Sending }
8,添加回調方法,代碼以下3d
private void Sending(IAsyncResult rec_socket) { Socket socket = (Socket)rec_socket.AsyncState; try { if (socket.Connected) { byte[] msgBuff = Encoding.UTF8.GetBytes(textBox1.Text); socket.Send(msgBuff); //socket.Accept(); } else { Console.WriteLine("Error!", "Error!"); } } catch { Console.WriteLine("Error!", "Error!"); } }
9,到此爲止,客戶端代碼已經完成,調試的時候先啓動服務端,而後啓動客戶端調試
10,運行截圖以下,點擊按鈕前,在文本框中輸入shixudong
11,點擊按鈕以後截圖以下
測試成功,有問題的能夠聯繫我shixudong3@yeah.net,但願能多你們有所幫助!