C # Socket Simple example (server communicates with client)

Source: Internet
Author: User

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?
    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[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 IP Address: port
  14. Serversocket.listen (10); //Set up to 10 queued connection requests
  15. Console.WriteLine ("boot listener {0} succeeded", ServerSocket.LocalEndPoint.ToString ());
  16. //Send data via Clientsoket
  17. Thread myThread = new Thread (listenclientconnect);
  18. Mythread.start ();
  19. Console.ReadLine ();
  20. }
  21. // <summary>
  22. /// Listening for client connections
  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 via Clientsocket
  46. int receivenumber = myclientsocket.receive (result);
  47. Console.WriteLine ("Receive 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 for the server side.

The complete code for the client is as follows:

Introduce a namespace:

[CSharp]View PlainCopyprint?
    1. Using System.Net;
    2. Using System.Net.Sockets;
    3. Using System.Threading;

Full code:

[CSharp]View PlainCopy print?
  1. Namespace Socketclient
  2. {
  3. Class Program
  4. {
  5. private static byte[] result = new byte[1024];
  6. static void Main (string[] args)
  7. {
  8. //Set 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 server IP with Port
  14. Console.WriteLine ("Connection server succeeded");
  15. }
  16. Catch
  17. {
  18. Console.WriteLine ("The connection server failed, please press ENTER to exit!")  ");
  19. return;
  20. }
  21. //Receive data via Clientsocket
  22. int receivelength = clientsocket.receive (result);
  23. Console.WriteLine ("Receive Server message: {0}", Encoding.ASCII.GetString (Result,0,receivelength));
  24. //Send data via Clientsocket
  25. For (int i = 0; i <; i++)
  26. {
  27. Try
  28. {
  29. Thread.Sleep (1000); //wait 1 seconds
  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 ("Send complete, press ENTER to exit");
  42. Console.ReadLine ();
  43. }
  44. }
  45. }


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)

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.