C # Socket programming (the simplest socket communication function)

Source: Internet
Author: User
Tags encode string

The sample program is a synchronous socket program, the function is very simple, just the client sends a message to the server, the server returns a message to the client, here is just a simple example, is a basic socket programming process, in the next article, will record the synchronization and asynchronous sockets, and their differences.

The following is a simple procedure for the sample program description

Server-side:

The first step: establish a endpoint to the image with the specified port number and the server's IP;

Step two: Create a socket pair image;

The third step: Bind the endpoint with the bind () method of the socket for the image;

Fourth step: Use the socket to the image of the Listen () method to start monitoring;

Fifth step: Accept the connection to the client, using the socket to the image of the Accept () method to create a new socket for the client like for and request communication;

Sixth step: After the communication end must remember to close the socket;


Code:

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Net;
Using System.net.sockets;namespace server
{
Class Program
{
static void Main (string[] args)
{
int port = 2000;
String host = "127.0.0.1";
Create an endpoint (EndPoint)
IPAddress IP = ipaddress.parse (host);//Convert IP address string to an instance of IPAddress type
IPEndPoint ipe = new IPEndPoint (IP, port);//Initializes a new instance of the IPEndPoint class with the specified port and IP
Create a socket and start listening
Socket s = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);//Create a socket pair image, if using the UDP protocol, You want to use a socket of type Sockettype.dgram
S.bind (IPE);//Bind endpoint to image (2000 port and IP address)
S.listen (0);//Start monitoring
Console.WriteLine ("Waiting for Client Connection");
Accept the client connection, create a new socket for this connection, and accept the information
Socket temp = s.accept ();//Create a new socket for new connection
Console.WriteLine ("Establish connection");
String recvstr = "";
byte[] recvbytes = new byte[1024];
int bytes;
bytes = Temp. Receive (Recvbytes, recvbytes.length, 0);//Receive information from the client
Recvstr + = Encoding.ASCII.GetString (recvbytes, 0, bytes);
Return information to client side
Console.WriteLine ("Server Get Message:{0}", recvstr);//Display the information from the client
String sendstr = "ok! Client Send Message successful! ";
byte[] bs = Encoding.ASCII.GetBytes (SENDSTR);
Temp. Send (BS, BS. Length, 0);//return information to the client
Temp. Close ();
S.close ();
Console.ReadLine ();
}

}
}

Server results:

Client:

The first step: establish a endpoint to the image with the specified port number and the server's IP;

Step two: Create a socket pair image;

The third step: using the socket to the image of the Connect () method with the above-established endpoint as parameters, to send a connection request to the server;

Fourth step: If the connection is successful, send the message to the server using the Send () method of the socket for the image;

Fifth step: Accept the message from the server using the receive () method of the socket to the image;

Sixth step: After the communication end must remember to close the socket;

Code:
Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Net;
Using System.net.sockets;namespace Client
{
Class Program
{
static void Main (string[] args)
{
Try
{
int port = 2000;
String host = "127.0.0.1"; To create an end point endpoint
IPAddress IP = ipaddress.parse (host);
IPAddress IPP = new IPAddress ("127.0.0.1");
IPEndPoint ipe = new IPEndPoint (IP, port);//convert IP and port to IPEndPoint instance
Create a socket and connect to the server
Socket c = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);//Create Socket
Console.WriteLine ("Conneting ...");
C.connect (IPE);//Connect to Server
Sending information to the server
String sendstr = "hello! This is a socket test ";
byte[] bs = Encoding.ASCII.GetBytes (SENDSTR);//encode string as Byte
Console.WriteLine ("Send Message");
C.send (BS, BS. Length, 0);//Send Message
Accept information returned from the server
String recvstr = "";
byte[] recvbytes = new byte[1024];
int bytes;
bytes = C.receive (recvbytes, recvbytes.length, 0);//Accept return information from server side
Recvstr + = Encoding.ASCII.GetString (recvbytes, 0, bytes);
Console.WriteLine ("Client Get message:{0}", recvstr);//display server return information///must remember to close after using the socket
C.close (); }
catch (ArgumentNullException e)
{
Console.WriteLine ("ArgumentNullException: {0}", e);
}
catch (SocketException E)
{
Console.WriteLine ("Socketexception:{0}", E);
} Console.WriteLine ("Press Enter to Exit");
}
}
}



Client Side results:

C # Socket programming (the simplest socket communication function)

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.