C # Socket Simple example (server communicates with client)

Source: Internet
Author: User

The complete code for the first outgoing server is as follows:

Using system;using system.collections.generic;using system.linq;using system.text;using  System.Net.Sockets;using System.Net;using System.Threading;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");  &Nbsp;          serversocket = new socket ( ADDRESSFAMILY.INTERNETWORK,&NBSP;SOCKETTYPE.STREAM,&NBSP;PROTOCOLTYPE.TCP);             serversocket.bind (New ipendpoint (Ip, myProt));   Bind IP Address: Port                Serversocket.listen (+)     //set up up to 10 queued connection requests                console.writeline ("Boot listener {0} succeeded",  ServerSocket.LocalEndPoint.ToString ());             //sending data via Clientsoket                Thread mythread = new thread (Listenclientconnect);             mythread.start ();     &nbsP;       console.readline ();         }        /// <summary>           ///  Monitoring 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                 {                     //receiving data via Clientsocket                        int receiveNumber =  Myclientsocket.receive (Result);                     console.writeline ("Receive client {0} message {1}",  MyClientSocket.RemoteEndPoint.ToString (), &NBSP;ENCODING.ASCII.GEtstring (result, 0, receivenumber));                 }                 catch  (Exception ex)                  {                     console.writeline (ex. Message);                     myclientsocket.shutdown (Socketshutdown.both);                     myclientsocket.close ();                      break;                }             }        }    }}

Client" is as follows:

Using system;using system.collections.generic;using system.linq;using system.text;using  System.Net;using System.Net.Sockets;using System.Threading;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))  //Configuring server IP and Ports                    console.writeline ("Connection server succeeded");             }             catch             {                 Console.WriteLine ("The connection server failed, please press ENTER to exit!") ");                return;             }      & nbsp;      //receive data via Clientsocket                int receivelength = clientsocket.receive (Result);             console.writeline ("Receive Server message: {0}",  Encoding.ASCII.GetString (result, 0, receivelength));             //sending data via  clientSocket                 for  (int i = 0; i < 10; i++)              {                 try                 {                      thread.sleep (+);     //wait 1 seconds                        string  sendmessage =  "CLIENT&NBSP;SEND&NBSP;MESSAGE&NBSP;HELLP"  + DateTime.Now;                      Clientsocket.send (Encoding.ASCII.GetBytes (sendMessage));                     console.writeline ("Send message to server: {0}"  +  sendmessage);                 }                catch                 {        &nbsP;            clientsocket.shutdown ( Socketshutdown.both);                     clientsocket.close ();                     break;                 }             }             Console.WriteLine ("Send complete, press ENTER to exit");             Console.ReadLine ();         }    }}

Run the server-side code first and then run the client-side code with the following results

Server

Client

Specific socket Knowledge: Http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket (v=vs.110). aspx?cs-save-lang=1 &cs-lang=csharp#code-snippet-2

This is the communication between server and client in the console, and the next step is to implement the communication between the server and the client in the window

C # Socket Simple example (server communicates with client)

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.