This example simply implements how to use the Socket class to implement connection-oriented communication.
Note: The purpose of this example is to illustrate the general idea of writing a program with sockets, rather than using the program in the actual project. In this case, there are actually many problems that are not solved, such as the message boundary problem, whether the port number is occupied, the parsing of the message command, and so on.
The following is the code for two programs (two programs are console programs)
The complete code for the first outgoing server is as follows:
Introduce a 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[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 IP Address: port
- Serversocket.listen (10); //Set up to 10 queued connection requests
- Console.WriteLine ("boot listener {0} succeeded", ServerSocket.LocalEndPoint.ToString ());
- //Send data via Clientsoket
- Thread myThread = new Thread (listenclientconnect);
- Mythread.start ();
- Console.ReadLine ();
- }
- // <summary>
- /// Listening for client connections
- // </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 via Clientsocket
- int receivenumber = myclientsocket.receive (result);
- Console.WriteLine ("Receive 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 for the server side.
The complete code for the client is as follows:
Introduce a namespace:
[CSharp]View PlainCopyprint?
- Using System.Net;
- Using System.Net.Sockets;
- Using System.Threading;
Full code:
[CSharp]View PlainCopy print?
- Namespace Socketclient
- {
- Class Program
- {
- private static byte[] result = new byte[1024];
- static void Main (string[] args)
- {
- //Set 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 server IP with Port
- Console.WriteLine ("Connection server succeeded");
- }
- Catch
- {
- Console.WriteLine ("The connection server failed, please press ENTER to exit!") ");
- return;
- }
- //Receive data via Clientsocket
- int receivelength = clientsocket.receive (result);
- Console.WriteLine ("Receive Server message: {0}", Encoding.ASCII.GetString (Result,0,receivelength));
- //Send data via Clientsocket
- For (int i = 0; i <; i++)
- {
- Try
- {
- Thread.Sleep (1000); //wait 1 seconds
- 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 ("Send complete, press ENTER to exit");
- Console.ReadLine ();
- }
- }
- }
After the compilation succeeds, the service side (server) is run and the client is run to achieve the communication effect.
Effects such as:
The program has passed the LAN test. (192.168.x.x)
If the compilation fails, you can download the project file at the following address:
http://download.csdn.net/source/3465765
C # Socket Simple example (server communicates with client)