C # network programming. Socket. tcplistener. tcpclient

Source: Internet
Author: User

This article describes the basic concepts of Network Programming Based on socket, including TCP protocol, socket, and two basic operations: listening port and remote server connection.

TCP isConnection-orientedIt means two remote hosts (or processes), because in fact remote communication is the communication between processes, while the process is running.Program), You must perform a handshake to confirm the connection is successful before the actual data can be transmitted. For example, if process a wants to send the string "It's a rainy world" to process B, it must first establish a connection. In this process, it first needs to know the location of process B (host address and port number ). Then we send a request message that does not contain actual data. We can call this message "hello ". If process B receives this "hello", it replies a "hello" to process a, and process a then sends the actual data "It's a rainy World ".

The second thing you need to know about TCP is that it isFull Duplex. It means that if the processes (such as process a and process B) on two hosts establish a connection, data can flow from A to B or B to. In addition, it is stillPoint-to-PointA TCP connection is always between the two. In sending, it is impossible to send data to multiple receivers through a connection. TCP also has a feature calledReliable Data TransmissionAfter the connection is established, the data transmission will surely arrive and be ordered. That is to say, when you send ABC, the receiving party will also receive ABC, instead of BCA or anything else.

One of the most important TCP-related concepts in programming isSocket. We should know the layer-7 network protocol. If we count the above application process, presentation layer, and Session Layer as one layer in general (some textbooks are divided in this way ), the network application program we wrote is located at the application layer, and we all know that TCP is a transport layer protocol, how can we use the transport layer service (message sending or file upload/download) at the application layer )? We all know that in an application, we use interfaces for separation. In the application layer and the transport layer, sockets are used for separation. It is like a small port opened by the transport layer for the application layer. The application sends data remotely or receives data remotely, that is, after the data enters this port, or before the data comes out of this port, we do not know or need to know, and we do not care about how it is transmitted, this belongs to other layers of the network. (For example, if you want to write an email to a friend from afar, we will take the lead in writing a letter, packaging a letter, and writing a letter at the application layer; when we put the mail into the mail box, the port of the mail box is the socket, after entering the socket, It is the transmission layer, network layer, etc. (Post Office, highway traffic management, or route) other levels of work. We never care about how the mail is sent from Xi'an to Beijing. We only know that it is okay to write the mail box. )

Next we will introduce how to program the network in C #.

Server

The first step is to enable listening to a port on the local machine. First, create a console application named "serverconsole", which represents our server. If you want to communicate with the outside world, the first thing to do is to enable listening to the port, which is like opening a "Door" for the computer ", all requests sent to this "Door" will be received by the system. In C #, follow these steps to create a system by using the local IP address and port number. net. sockets. tcplistener-type instance, and then call the START () method on the instance to enable listening on the specified port.

 
UsingSystem;

UsingSystem. Collections. Generic;

 
UsingSystem. LINQ;

 
UsingSystem. text;

 
UsingSystem. net;

 
UsingSystem. net. Sockets;

 
 

 
NamespaceSockstest

 
{

 
ClassProgram

{

 
Static VoidMain (String[] ARGs)

 
{

 
Console. writeline ("Server is running ...");

 
IPaddress IP =NewIPaddress (New Byte[] {127, 0, 0, 1 });

 
Tcplistener listener =NewTcplistener (IP address, 8500 );

 
 

Listener. Start ();// Start listening

 
Console. writeline ("Start listening ...");

 
 

 
Tcpclient remoteclient = listener. accepttcpclient ();// Accept pending connection requests

 
Console. writeline ("Client Connected! {0} <-- {1 }",

 
Remoteclient. Client. localendpoint. tostring (), remoteclient. Client. remoteendpoint. tostring ());

 
Console. Read ();

}

 
}

 
}

 

.Code, We have enabled listening to port 8500. After running the above program, open the "command prompt" and enter "netstat-a" to view the status of all opened ports on the computer. You can find Port 8500 and see that its status is listening. This indicates that it has started listening:

 

Client:

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. net. sockets; namespace socksclient {class program {static void main (string [] ARGs) {console. writeline ("client is running ...... "); tcpclient = new tcpclient (); try {tcpclient. connect ("localhost", 8500);} catch (exception e) {console. writeline (E. tostring (); console. read (); return;} console. W Riteline ("server connected! {0} --> {1} ", tcpclient. Client. localendpoint. tostring (), tcpclient. Client. remoteendpoint. tostring (); console. Read ();}}}

 

When server is enabled and client is enabled, the connection status is displayed on the server.

 

Next, obtain the multi-client connection.

Modified client code

 using system; using system. collections. generic; using system. LINQ; using system. text; using system. net. sockets; namespace socksclient {class program {static void main (string [] ARGs) {console. writeline ("client is running ...... "); tcpclient; For (INT I = 0; I <5; I ++) {try {tcpclient = new tcpclient (); tcpclient. connect ("localhost", 85 00); console. writeline ("server connected! {0} --> {1} ", tcpclient. client. localendpoint. tostring (), tcpclient. client. remoteendpoint. tostring ();} catch (exception e) {console. writeline (E. tostring (); console. read (); Return ;}} console. read () ;}}

 

Modified server code

 
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. net; using system. net. sockets; namespace sockstest {class program {static void main (string [] ARGs) {console. writeline ("server is running... "); IPaddress IP = new IPaddress (New byte [] {127, 0, 0, 1}); tcplistener listener = new tcplistener (IP, 8500); listener. start (); // start listening to the console. writeline ("START L Istening... "); While (true) {tcpclient remoteclient = listener. accepttcpclient (); // accept the pending connection request console. writeline (" Client Connected! {0} <-- {1} ", remoteclient. client. localendpoint. tostring (), remoteclient. client. remoteendpoint. tostring ();} console. read ();}}}

 

Effect after running

 

Microsoft has made a good encapsulation of the above. It is easy to use here.

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.