Simplified description C # basic socket programming example

Source: Internet
Author: User
Tags socket connect

This exampleProgramIt is a synchronous socket program. Its function is very simple. It only sends a message from the client to the server, and the server returns a message to the client. Here is just a simple example. It is the most basic socket programming process, in the followingArticleThe synchronization and Asynchronization of sockets and their differences are recorded in sequence.

 

The following describes the simple steps of the sample program.

Server:

Step 1: Create an endpoint image with the specified port number and the server IP address;

Step 2: Create a socket image;

Step 3: bind an endpoint using the BIND () method of the socket image;

Step 4: Use the socket to start listening to the listen () method of the image;

Step 5: accept the connection to the client, and use the socket to create a new socket to communicate with the requested client using the accept () method of the image;

Step 6: Close the socket after the communication ends;

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)
IPaddress IP = IPaddress. parse (host); // converts an IP address string to an instance of the IPaddress type.
Ipendpoint IPE = new ipendpoint (IP, Port); // use the specified port and IP address to initialize a new instance of the ipendpoint class.

// create a socket and start listening
socket S = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); // create a socket image. If UDP is used, use sockettype. dgram socket
S. BIND (IPE); // bind the endpoint (port 2000 and IP address)
S. listen (0); // start listening
console. writeline ("waiting for client connection");

// accept the client connection, create a new socket for the connection, and accept the Information
socket temp = S. accept (); // create a new socket for the 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 the client
Console. writeline ("Server get message: {0}", recvstr); // display information sent 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 result:

Client:

Step 1: Create an endpoint image with the specified port number and the server IP address;

Step 2: Create a socket image;

Step 3: Use the socket connect () method of the image to establish an endpoint object as a parameter and send a connection request to the server;

Step 4: If the connection is successful, use the send () method of the socket to send information to the server;

Step 5: Use the socket-to-image receive () method to receive information sent from the server;

Step 6: Close the socket after the communication ends;
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 ";
/// Create an endpoint
IPaddress IP = IPaddress. parse (host );
// IPaddress IPP = new IPaddress ("127.0.0.1 ");
Ipendpoint IPE = new ipendpoint (IP, Port); // converts the IP address and port to an ipendpoint instance.

/// Create a socket and connect to the server
Socket c = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP); // create a socket
Console. writeline ("conneting... ");
C. Connect (IPE); // connect to the server

/// Send information to the server
String sendstr = "Hello! This is a socket test ";
Byte [] BS = encoding. ASCII. getbytes (sendstr); // encode the string as a byte
Console. writeline ("Send message ");
C. Send (BS, BS. length, 0); // send information

/// Accept the information returned from the server
String recvstr = "";
Byte [] recvbytes = new byte [1, 1024];
Int bytes;
Bytes = C. Receive (recvbytes, recvbytes. length, 0); // The slave server accepts the returned information.
Recvstr + = encoding. ASCII. getstring (recvbytes, 0, bytes );
Console. writeline ("client get message: {0}", recvstr); // display the Server Response Information
/// Remember to close the socket after it is used up
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 result:

This example program is a synchronous socket program. The function is very simple, but the client sends a message to the server, and the server returns a message to the client. Here is just a simple example, it is the most basic socket programming process. In the next article, the synchronization and Asynchronization of sockets and their differences will be recorded in sequence.

 

The following describes the simple steps of the sample program.

Server:

Step 1: Create an endpoint image with the specified port number and the server IP address;

Step 2: Create a socket image;

Step 3: bind an endpoint using the BIND () method of the socket image;

Step 4: Use the socket to start listening to the listen () method of the image;

Step 5: accept the connection to the client, and use the socket to create a new socket to communicate with the requested client using the accept () method of the image;

Step 6: Close the socket after the communication ends;

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)
IPaddress IP = IPaddress. parse (host); // converts an IP address string to an instance of the IPaddress type.
Ipendpoint IPE = new ipendpoint (IP, Port); // use the specified port and IP address to initialize a new instance of the ipendpoint class.

/// Create a socket and start listening
Socket S = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP); // create a socket image. If UDP is used, use a socket of the sockettype. dgram type.
S. BIND (IPE); // bind the endpoint to the image (port 2000 and IP address)
S. Listen (0); // start listening
Console. writeline ("waiting for client connection ");

// accept the client connection, create a new socket for the connection, and accept the Information
socket temp = S. accept (); // create a new socket for the 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 the client
Console. writeline ("Server get message: {0}", recvstr); // display information sent 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 result:

Client:

Step 1: Create an endpoint image with the specified port number and the server IP address;

Step 2: Create a socket image;

Step 3: Use the socket connect () method of the image to establish an endpoint object as a parameter and send a connection request to the server;

Step 4: If the connection is successful, use the send () method of the socket to send information to the server;

Step 5: Use the socket-to-image receive () method to receive information sent from the server;

Step 6: Close the socket after the communication ends;
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 ";
/// Create an endpoint
IPaddress IP = IPaddress. parse (host );
// IPaddress IPP = new IPaddress ("127.0.0.1 ");
Ipendpoint IPE = new ipendpoint (IP, Port); // converts the IP address and port to an ipendpoint instance.

/// Create a socket and connect to the server
Socket c = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP); // create a socket
Console. writeline ("conneting... ");
C. Connect (IPE); // connect to the server

/// Send information to the server
String sendstr = "Hello! This is a socket test ";
Byte [] BS = encoding. ASCII. getbytes (sendstr); // encode the string as a byte
Console. writeline ("Send message ");
C. Send (BS, BS. length, 0); // send information

/// Accept the information returned from the server
String recvstr = "";
Byte [] recvbytes = new byte [1, 1024];
Int bytes;
Bytes = C. Receive (recvbytes, recvbytes. length, 0); // The slave server accepts the returned information.
Recvstr + = encoding. ASCII. getstring (recvbytes, 0, bytes );
Console. writeline ("client get message: {0}", recvstr); // display the Server Response Information
/// Remember to close the socket after it is used up
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 result:

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.