1. Add two windows form projects, one as the server and the other as the Client.
2. Add the server code and namespace. Add the TextBox Control on the interface.
Copy codeThe Code is as follows:
Using System. Net;
Using System. Net. Sockets;
3. Add code using the FormLoad Method
Copy codeThe Code is as follows:
Private void Form1_Load (object sender, EventArgs e)
{
IPEndPoint epServer = new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 7878); // IP address and port number
Socket socket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp); // define the socket
Socket. Bind (epServer); // Bind
Socket. Listen (10); // Listen
Socket. BeginAccept (new AsyncCallback (RecVing), socket); // asynchronous receiving, callback method: RecVing
}
4. Add the callback method code
Copy codeThe Code is as follows:
Private void RecVing (IAsyncResult rec_socket)
{
String comment STR = "";
Socket SC = (Socket) rec_socket.AsyncState;
Socket socket = SC. EndAccept (rec_socket );
Byte [] bytes = new byte [1, 1024];
Int I = socket. Receive (bytes );
Required STR = Encoding. UTF8.GetString (bytes, 0, I );
Showstrs (reverse Str );
SC. BeginAccept (new AsyncCallback (RecVing), SC );
}
5. Add the showstrs method,
Define private delegate void shixudong_invoke (string invokefun );
Copy codeThe Code is as follows:
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. By now, the server has been added
7. client code. Add a namespace and add a button event on the interface, just like the server.
Copy codeThe Code is as follows:
Private void button#click (object sender, EventArgs e)
{
IPEndPoint = new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 7878); // IP address, Port Number
Socket socket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Socket. BeginConnect (IPEndPoint, new AsyncCallback (Sending), socket); // callback method Sending
}
8. Add the callback method. The Code is as follows:
Copy codeThe Code is as follows:
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. By now, the client code has been completed. Start the server before debugging.
10. Run the following command. before clicking the button, enter shixudong in the text box.