C #. NET network program development-TCP

Source: Internet
Author: User
Tags getstream
Previous Article Visual C #. NET network Program Development-socket: classes that support HTTP, TCP, and UDP form a layer-3 TCP/IP model (Request Response layer, application protocol layer, and Transport Layer) the middle layer-application protocol layer. The analogy of this layer is located at the bottom layer of the socket class to provide a higher level of abstraction. They encapsulate the creation of TCP and UDP sockets and do not need to process the connection details, this allows us to use more tcpclient, udpclient, and tcplistener when writing socket-level protocols, rather than writing them directly to the socket. The hierarchical relationship between them is shown as follows:
It can be seen that the tcpclient class is built based on the socket class, which is the foundation for providing TCP services with a higher degree of abstraction. Because of this, many communication protocols on the application layer, such as the file transfer protocol (FTP) and HTTP (hypertext transfers Protocol) hypertext Transfer Protocol is directly created on tcpclient and other classes.
The tcpclient class uses TCP to request data from Internet resources. Establish a connection with the remote endpoint over TCP, and then use this connection to send and receive data packets. TCP is responsible for ensuring that packets are sent to the end point and combined in the correct order when the packets arrive.
From the name, we can see that the tcpclient class is designed for clients and provides client connections for TCP network services. Tcpclient provides a simple method to connect, send, and receive data over a network.
To establish a TCP connection, you must know the IP address of the network device that hosts the required service and the TCP port used for communication ). Internet Assigned Numbers Authority (IANA) defines the port number of the Public Service (you can access http://www.iana.org/assignments/port-numbers for more detailed information ). Services not in the IANA list can use port numbers in the range of 1,024 to 65,535. To create such a connection, you can use one of the three constructors of the tcpclient class:
1. Public tcpclient () when using this constructor without any parameters, the default IP address of the local machine is used and the default communication port number is 0. In this case, if there is more than one IP address on the local machine, you cannot choose to use it. The following statement demonstrates how to use the default constructor to create a new tcpclient:
Tcpclient tcpclientc = new tcpclient ();
2. Public tcpclient (ipendpoint) uses the local ipendpoint to create a tcpclient instance object. As described in the previous article, ipendpoint represents the network endpoint as an IP address and port number. Here it is used to specify the local network interface (IP address) and port number used to establish a remote host connection, this constructor provides a choice for using the local IPaddress and port. The following statement demonstrates how to use a local endpoint to create a tcpclient class instance:
Iphostentry ipinfo = DNS. gethostbyname ("www.tuha.net"); // host information
Ipaddresslist [] iplist = ipinfo. Addresslist; // ip address Array
IPaddress IP = iplist [0]; // The first IP address is usually used for multiple IP addresses.
Ipendpoint ipep = new ipendpoint (IP, 4088); // obtain the network endpoint
Try {
Tcpclient tcpclienta = new tcpclient (iplocalendpoint );
} Catch (exception e ){
Console. writeline (E. tostring ());
}
At this point, you may be confused. The client needs to create a connection with the server. The specified IP address and communication port number should be from the remote server! In fact, with the above two constructor, all you need to do is bind the tcpclient instance object to the IP address and port to complete the connection, you also need to explicitly specify the connection to the remote host, which can be achieved through the tcpclient connect method. The connet method uses the specified host name and port number to connect the client to the remote host:
1) Public void connect (ipendpoint); Use the specified remote network endpoint to connect the client to the remote TCP host.
Public void connect (IPaddress, INT); Connect the client to the TCP host using the specified IP address and port number.
Public void connect (string, INT); connects the client to the specified port on the specified host.
It should be noted that the ipendpoint network endpoint parameter in all the reloads of the Connect Method
Node, IPaddress, And the DNS host name and port pointed out by INT indicate the remote server.
The following example uses the default Host IP address and port number 0 to establish a connection with the remote host:
Tcpclient = new tcpclient (); // create a tcpclient object instance
Try {
Tcpclient. Connect ("www.contoso.com", 11002); // establish a connection
}
Catch (exception e ){
Console. writeline (E. tostring ());
}
3. Public tcpclient (string, INT); initialize a new instance of the tcpclient class and connect it to the specified port on the specified host. Unlike the first two constructors, this constructor automatically establishes a connection and you do not need to call the connect method. The string type parameter indicates the DNS name of the remote host, for example, www.tuha.net.
The following example calls this method to connect to the host with the specified host name and port number:
Try {
Tcpclient tcpclientb = new tcpclient ("www.tuha.net", 4088 );
}
Catch (exception e ){
Console. writeline (E. tostring ());
}
As we mentioned above, the tcpclient class is created on the socket and provides a higher level of abstraction in the TCP Service, which is reflected in the transmission and acceptance of network data, tcpclient uses the standard stream processing technology to make it easier and more intuitive to read and write data ,. the. NET Framework is responsible for providing richer structures for stream processing throughout the entire process. the stream in the. NET Framework has wider compatibility, the general method built on more general stream operations makes us no longer need to be confused with the actual content of the file (HTML, XML, or any other content ), all applications will use the same method (stream. write, stream. read) sends and receives data. In addition, the stream provides real-time access to data when data is downloaded from the Internet. You can process some data immediately when it arrives without waiting for the application to download the complete dataset .. Net implements these processing technologies through the networkstream class.
The networkstream class is included in the system. net. Sockets namespace Of the. NET Framework. This class provides basic data streams for network access. Networkstream provides a standard. NET Framework Stream Mechanism for sending and receiving data through network sockets. Networkstream supports synchronous and asynchronous access to network data streams. Networkstream inherits from stream, which provides a rich set of methods and attributes for convenient network communication.
Like all other streams inherited from the abstract base-class stream, networkstream network streams can also be considered as a data channel between the data source end (customer client) and the receiving end (Service Server, the subsequent data reading and writing are based on this channel.
In the. NET Framework, networkstream supports two operations:
1. Write a stream. Write data is transmitted from the data structure to the stream.
2. Read the stream. Read data is transmitted from the stream to the data structure (such as byte arrays.
Different from a normal stream, a network stream does not have a uniform concept of the current position. Therefore, it does not support searching and random access to data streams. The corresponding attribute canseek always returns false, and the seek and Position Methods also lead to notsupportedexception.
For socket-based application protocols, you can obtain networkstream network data streams in the following two ways:
1. Use the networkstream constructor: Public networkstream (socket, fileaccess, bool); (there are overload methods ), it uses the specified access permission and the specified socket permission to create a new networkstream class instance for the specified socket. before using it, you need to create a socket object instance and use the socket. the connect method establishes a connection with the remote server before you can use this method to obtain the network transmission stream. Example:
Socket S = new socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP); // create a client socket object instance
Try {
S. Connect ("www.tuha.net", 4088); // establish a connection with the remote host
}
Catch (exception e ){
MessageBox. Show ("connection error:" + E. Message );
}
Try {
Networkstream stream = new networkstream (S, fileaccess. readwrite, false); // obtain the network transmission stream
}
2. Use the tcpclient. getstream method: Public networkstream etstream (); it returns the networkstream of the basic network stream used to send and receive data. Getstream uses the basic socket as its constructor parameter to create an instance of the networkstream class. Before using tcpclient, you need to create a tcpclient object instance and establish a connection with the remote host, for example:
Tcpclient = new tcpclient (); // create a tcpclient object instance
Try {
Tcpclient. Connect ("www.tuha.net", 4088); // try to connect to the remote host}
Catch (exception e ){
MessageBox. Show ("connection error:" + E. Message );
}
Try {
Networkstream stream = tcpclient. getstream (); // gets the network transmission stream
}
Catch (exception E)
{
MessageBox. Show ("tcpclient error:" + E. Message );
}
After obtaining the networkstream network stream through the above method, you can use the standard stream read/write method write and read to send and accept data.
The above uses the tcpclient class in. Net to implement client programming. Technical materials In order to provide these services to the client, we also need to compile the corresponding server program, the previous article "Visual C #. net network program development-socket mentioned above that socket, as the basis of other network protocols, can be used for both client-side development and server-side development, and is widely used in the transmission layer, on the application protocol layer, we use tcpclient built on the socket class to replace the socket. Correspondingly, tcplistener built on the socket provides a higher level of TCP Service, this makes it easier for us to write server applications. For this reason, application layer protocols such as FTP and HTTP are built on the basis of the tcplistener class.
. The tcplistener in. NET is used to monitor incoming requests on the TCP port and create a tcplistener object instance by binding the local IP address and the corresponding port (the two must be consistent with the client request, the start method starts the listener. After tcplistener listens to the connection to the client, it accepts the incoming connection request and creates a tcpclient to process the request according to the different request methods of the client, alternatively, you can use the acceptsocket method to accept incoming connection requests and create a socket to process the requests. Finally, you need to use stop to disable the socket used to listen for incoming connections. You must also disable any instances returned from the acceptsocket or accepttcpclient. This process is described as follows:
First, create a tcplistener object instance, which is implemented through the construction method of the tcplistener class:
Public tcplistener (port); // specifies the local port
Public tcplistener (ipendpoint) // specifies the local endpoint
Public tcplistener (IPaddress, Port) // specify the local IP address and port
The parameters mentioned in the preceding method are not described here. The only reminder is that these parameters are for the server host. The following example shows how to create a tcplistener class:
Iphostentry ipinfo = DNS. Resolve ("127.0.0.1"); // host information
Ipaddresslist [] iplist = ipinfo. ipaddresslist; // ip Array
IPaddress IP = iplist [0]; // ip
Try {
Tcplistener = new tcplistener (IPaddress, 4088); // create a tcplistener object instance to listen on client connections
}
Catch (exception e ){
MessageBox. Show ("tcplistener error:" + E. Message );
}
Then, you need to call the start method to start listening:
Public void start ();
Second, when listening to a client connection, you need to accept the pending connection request, which completes the connection by calling one of the following two methods:
Public socket acceptsocket ();
Public tcpclient accepttcpclient ();
The previous method returns the socket object representing the client, and then communicates with the remote computer through the send and receive methods of the socket class. The other method returns the tcpclient object representing the client, then use the tcpclient described above. the getstream method obtains the networkstream of the basic network stream of tcpclient and uses the stream read/write method to communicate with remote computers.
Finally, remember to disable the listener: Public void stop ();
Close other connected instances at the same time: Public void close ();
The following example fully demonstrates the process above: bool done = false;
Tcplistener listener = new tcplistener (13); // create a tcplistener object instance (Port 13 provides time service)
Listener. Start (); // start the listener
While (! Done) {// enter the infinite loop to listen for user connections
Tcpclient client = listener. accepttcpclient (); // create a client to connect to tcpclient after listening to the connection
Networkstream NS = client. getstream (); // obtain the network transmission stream
Byte [] bytetime = encoding. ASCII. getbytes (datetime. Now. tostring (); // pre-sent content (this is the server time) is converted to a byte array for writing streams
Try {
NS. Write (bytetime, 0, bytetime. Length); // write stream
NS. Close (); // close the stream
Client. Close (); // close the Client Connection
}
Catch (exception e ){
MessageBox. Show ("stream error:" + E. Message)
}
Based on the above knowledge, the following instances implement simple network communication-Dual-host interconnection, and develop applications for the client and server respectively. The client creates a connection to the server, sends a connection request connection signal to the remote host, and sends the conversation content. The remote host receives the connection from the client and sends a confirmation connection signal to the client, receive and display the client conversation content at the same time. Based on this, you can use your creativity to develop a chat room based on programming language (C!
Client main Source code :
Public void sendmeg () // send message
{
Try
{
Int Port = int32.parse (textbox3.text. tostring (); // remote host port
Try
{
Tcpclient = new tcpclient (textbox1.text, Port); // create a tcpclient object instance}
Catch (exception le)
{
MessageBox. Show ("tcpclient error:" + Le. Message );
}
String strdateline = datetime. Now. tow.datestring () + "" + datetime. Now. tolongtimestring (); // get the client time when sending
Netstream = tcpclient. getstream (); // get the network stream
Sw = new streamwriter (netstream); // create a textwriter and write characters to the stream
String words = textbox4.text; // to be sent
String content = strdateline + words; // content to be sent
Sw. Write (content); // write stream
Sw. Close (); // close the stream writer.
Netstream. Close (); // disable network streams
Tcpclient. Close (); // close the Client Connection
}
Catch (exception ex)
{
MessageBox. Show ("Sending Message failed! "+ Ex. Message );
}
Textbox4.text = ""; // clear
}
Main server Source Code :
Public void startlisten () // listen for user requests on specific ports
{
// Receivemeg ();
Islinked = false; // connection flag
Try
{Int Port = int32.parse (textbox1.text. tostring (); // The local listening port.
Serverlistener = new tcplistener (port); // create a tcplistener object instance
Serverlistener. Start (); // start the listener
}
Catch (exception ex)
{
MessageBox. Show ("can't start server" + ex. Message );
Return;
}
Islinked = true;
While (true) // enter the infinite loop and wait for the client to connect
{
Try
{
Tcpclient = serverlistener. accepttcpclient (); // create a client connection object
Netstream = tcpclient. getstream (); // get the network stream
Sr = new streamreader (netstream); // stream Reader
}
Catch (exception re)
{
MessageBox. Show (Re. Message );
}
String Buffer = "";
String received = "";
Written ed + = Sr. Readline (); // read a row in the stream
While (received. length! = 0)
{
Buffer + = received;
Buffer + = "\ r \ n ";
// Received = "";
Written ED = Sr. Readline ();
}
Listbox1.items. Add (buffer); // display
// Close
Sr. Close ();
Netstream. Close ();
Tcpclient. Close ();
}
} Transferred from: http://blog.sina.com.cn/s/blog_4efce4d10100ckwj.html ~ Type = v5_one & label = rela_prevarticle
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.