Basic socket programming C #

Source: Internet
Author: User

Note: This example runs in. net2005 "XP through

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 communicationSocket;

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 an endpoint 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 this connection, and accept the information
Socket temp = S. Accept (); // Create a new socket for the new connection
Console. writeline ( " Establish a connection " );
String Recvstr = "" ;
Byte [] Recvbytes = New Byte [ 1024 ];
Int Bytes;
Bytes
= Temp. Receive (recvbytes, recvbytes. length, 0 ); // Accept information from the client
Recvstr + = Encoding. ASCII. getstring (recvbytes, 0 , Bytes );


///Return information to the client
Console. writeline ( " Server get message: {0} " , Recvstr ); // Display the 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: Use the specified port number andIPCreateEndpointObject;

Step 2: CreateSocketObject;

Step 3: UseSocketObjectConnect ()MethodEndpointAs a parameter, a connection request is sent to the server;

Step 4: UseSocketObjectSend ()Method to send information to the server;

Step 5: UseSocketObjectReceive ()Method to receive messages from the server;

Step 6: Close the communicationSocket;

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 ); // Convert IP addresses and ports to ipendpoint instances


///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 the server


///Send messages to servers
String Sendstr = " Hello! This is a socket Test " ;
Byte [] BS = Encoding. ASCII. getbytes (sendstr ); // Encodes a string into bytes.
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 [ 1024 ];
Int Bytes;
Bytes
= C. Receive (recvbytes, recvbytes. length, 0 ); // Accept returned information from the server
Recvstr + = Encoding. ASCII. getstring (recvbytes, 0 , Bytes );
Console. writeline (
" Client get message: {0} " , Recvstr ); // Display 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:
 

Trackback: http://www.cnblogs.com/sopper/archive/2007/01/23/627924.aspx

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.