This article Reprinted from: http://blog.csdn.net/andrew_wx/article/details/6629721
This example simply shows how to use the socket class to implement connection-oriented communication.
Note: The purpose of this example is to explain the general idea of writing a program using socket, rather than the actual project. In this example, there are still many unsolved problems, such as the message boundary problem, whether the port number is occupied, and the message Command Parsing problem ..
The following is the code of two programs (both of them are console programs)
The complete server code is as follows:
Introduce namespace:
[CSHARP]View plaincopyprint?
- Using system. net. Sockets;
- Using system. net;
- Using system. Threading;
The complete code is as follows:
[CSHARP]View plaincopyprint?
- Namespace socketserver
- {
- Class Program
- {
- Private Static byte [] result = new byte [1, 1024];
- Private Static int myprot = 8885; // Port
- Static socket serversocket;
- Static void main (string [] ARGs)
- {
- // Server IP Address
- IPaddress IP = IPaddress. parse ("127.0.0.1 ");
- Serversocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
- Serversocket. BIND (New ipendpoint (IP, myprot); // bind an IP Address: Port
- Serversocket. Listen (10); // you can specify up to 10 queued connection requests.
- Console. writeline ("listener started {0} succeeded", serversocket. localendpoint. tostring ());
- // Send data through clientsoket
- Thread mythread = new thread (listenclientconnect );
- Mythread. Start ();
- Console. Readline ();
- }
- /// <Summary>
- /// Listen for client connection
- /// </Summary>
- Private Static void listenclientconnect ()
- {
- While (true)
- {
- Socket clientsocket = serversocket. Accept ();
- Clientsocket. Send (encoding. ASCII. getbytes ("server say hello "));
- Thread receivethread = new thread (receivemessage );
- Receivethread. Start (clientsocket );
- }
- }
- /// <Summary>
- /// Receive messages
- /// </Summary>
- /// <Param name = "clientsocket"> </param>
- Private Static void receivemessage (Object clientsocket)
- {
- Socket myclientsocket = (socket) clientsocket;
- While (true)
- {
- Try
- {
- // Receive data through clientsocket
- Int receivenumber = myclientsocket. Receive (result );
- Console. writeline ("receiving client {0} message {1}", myclientsocket. remoteendpoint. tostring (), encoding. ASCII. getstring (result, 0, receivenumber ));
- }
- Catch (exception ex)
- {
- Console. writeline (ex. Message );
- Myclientsocket. Shutdown (socketshutdown. Both );
- Myclientsocket. Close ();
- Break;
- }
- }
- }
- }
- }
The above is the complete code of the server.
The complete code of the client is as follows:
Introduce namespace:
[CSHARP]View plaincopyprint?
- Using system. net;
- Using system. net. Sockets;
- Using system. Threading;
Complete code:
[CSHARP]View plaincopyprint?
- Namespace socketclient
- {
- Class Program
- {
- Private Static byte [] result = new byte [1, 1024];
- Static void main (string [] ARGs)
- {
- // Set the Server IP Address
- IPaddress IP = IPaddress. parse ("127.0.0.1 ");
- Socket clientsocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
- Try
- {
- Clientsocket. Connect (New ipendpoint (IP, 8885); // Configure the server IP address and port
- Console. writeline ("successfully connected to the server ");
- }
- Catch
- {
- Console. writeline ("failed to connect to the server. Press enter to exit! ");
- Return;
- }
- // Receive data through clientsocket
- Int incluelength = clientsocket. Receive (result );
- Console. writeline ("received Server Message: {0}", encoding. ASCII. getstring (result, 0, cancelength ));
- // Send data through clientsocket
- For (INT I = 0; I <10; I ++)
- {
- Try
- {
- Thread. Sleep (1000); // wait 1 second
- String sendmessage = "client send message hellp" + datetime. now;
- Clientsocket. Send (encoding. ASCII. getbytes (sendmessage ));
- Console. writeline ("send message to server: {0}" + sendmessage );
- }
- Catch
- {
- Clientsocket. Shutdown (socketshutdown. Both );
- Clientsocket. Close ();
- Break;
- }
- }
- Console. writeline ("sent, press enter to exit ");
- Console. Readline ();
- }
- }
- }
After the compilation is successful, run the server and then the client to achieve the communication effect.
The effect is as follows:
The program has passed the LAN test. (192.168.x.x)
If compilation fails, you can download the project file at the following address:
Http://download.csdn.net/source/3465765