(Conversion) C # socket simple example (communication between the server and the client)

Source: Internet
Author: User

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?
  1. Using system. net. Sockets;
  2. Using system. net;
  3. Using system. Threading;

 

 

The complete code is as follows:

 

[CSHARP]View plaincopyprint?
  1. Namespace socketserver
  2. {
  3. Class Program
  4. {
  5. Private Static byte [] result = new byte [1, 1024];
  6. Private Static int myprot = 8885; // Port
  7. Static socket serversocket;
  8. Static void main (string [] ARGs)
  9. {
  10. // Server IP Address
  11. IPaddress IP = IPaddress. parse ("127.0.0.1 ");
  12. Serversocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
  13. Serversocket. BIND (New ipendpoint (IP, myprot); // bind an IP Address: Port
  14. Serversocket. Listen (10); // you can specify up to 10 queued connection requests.
  15. Console. writeline ("listener started {0} succeeded", serversocket. localendpoint. tostring ());
  16. // Send data through clientsoket
  17. Thread mythread = new thread (listenclientconnect );
  18. Mythread. Start ();
  19. Console. Readline ();
  20. }
  21. /// <Summary>
  22. /// Listen for client connection
  23. /// </Summary>
  24. Private Static void listenclientconnect ()
  25. {
  26. While (true)
  27. {
  28. Socket clientsocket = serversocket. Accept ();
  29. Clientsocket. Send (encoding. ASCII. getbytes ("server say hello "));
  30. Thread receivethread = new thread (receivemessage );
  31. Receivethread. Start (clientsocket );
  32. }
  33. }
  34. /// <Summary>
  35. /// Receive messages
  36. /// </Summary>
  37. /// <Param name = "clientsocket"> </param>
  38. Private Static void receivemessage (Object clientsocket)
  39. {
  40. Socket myclientsocket = (socket) clientsocket;
  41. While (true)
  42. {
  43. Try
  44. {
  45. // Receive data through clientsocket
  46. Int receivenumber = myclientsocket. Receive (result );
  47. Console. writeline ("receiving client {0} message {1}", myclientsocket. remoteendpoint. tostring (), encoding. ASCII. getstring (result, 0, receivenumber ));
  48. }
  49. Catch (exception ex)
  50. {
  51. Console. writeline (ex. Message );
  52. Myclientsocket. Shutdown (socketshutdown. Both );
  53. Myclientsocket. Close ();
  54. Break;
  55. }
  56. }
  57. }
  58. }
  59. }

 

 

The above is the complete code of the server.

 

The complete code of the client is as follows:

 

Introduce namespace:

 

[CSHARP]View plaincopyprint?
  1. Using system. net;
  2. Using system. net. Sockets;
  3. Using system. Threading;

 

 

Complete code:

 

[CSHARP]View plaincopyprint?
  1. Namespace socketclient
  2. {
  3. Class Program
  4. {
  5. Private Static byte [] result = new byte [1, 1024];
  6. Static void main (string [] ARGs)
  7. {
  8. // Set the Server IP Address
  9. IPaddress IP = IPaddress. parse ("127.0.0.1 ");
  10. Socket clientsocket = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP );
  11. Try
  12. {
  13. Clientsocket. Connect (New ipendpoint (IP, 8885); // Configure the server IP address and port
  14. Console. writeline ("successfully connected to the server ");
  15. }
  16. Catch
  17. {
  18. Console. writeline ("failed to connect to the server. Press enter to exit! ");
  19. Return;
  20. }
  21. // Receive data through clientsocket
  22. Int incluelength = clientsocket. Receive (result );
  23. Console. writeline ("received Server Message: {0}", encoding. ASCII. getstring (result, 0, cancelength ));
  24. // Send data through clientsocket
  25. For (INT I = 0; I <10; I ++)
  26. {
  27. Try
  28. {
  29. Thread. Sleep (1000); // wait 1 second
  30. String sendmessage = "client send message hellp" + datetime. now;
  31. Clientsocket. Send (encoding. ASCII. getbytes (sendmessage ));
  32. Console. writeline ("send message to server: {0}" + sendmessage );
  33. }
  34. Catch
  35. {
  36. Clientsocket. Shutdown (socketshutdown. Both );
  37. Clientsocket. Close ();
  38. Break;
  39. }
  40. }
  41. Console. writeline ("sent, press enter to exit ");
  42. Console. Readline ();
  43. }
  44. }
  45. }


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.