The previous "Visual C # .NET Network Program Development-Socket" said: Support HTTP, TCP and UDP classes constitute an intermediate layer of TCP / IP three-layer model (request response layer, application protocol layer, transport layer) - Application Protocol layer, the class of the layer provides a higher level of abstraction than at the bottom of the Socket class, which encapsulates the creation of TCP and UDP sockets, does not need to handle the details of the connection, which makes us in writing socket level Attempts, you can try more to use TcpClient, udpclient, and tcplistener more, not directly to the Socket. This level of relationship between them is as follows:
It can be seen that the TCPCLIENT class is based on the Socket class, which is the basis for providing TCP services at a higher abstraction. Because of this, communication protocols on many application layers, such as FTP (File Transfer "file transfer protocol, HTTP (Hypertext TransferS Protocol) hyper text transfer protocols, etc., are directly above TCPClient.
The TCPCLIENT class uses TCP request data from the Internet resource. The TCP protocol establishes a connection with the remote endpoint and then uses this connection to send and receive the packet. TCP is responsible for ensuring that the packet is sent to the endpoint and combined in the correct order when the packet arrives.
From the name, you can see that the TCPClient class is designed for the client, which provides a client connection for TCP network services. TCPClient provides a simple way to send and receive data over a network connection.
To establish a TCP connection, you must know the address (iPadDress) of the network device that carries the required service, and the TCP port (Port) of the service for communication. Internet Assigned Numbers Authority (IANA) Defines the port number of public services (you can access http://www.iana.org/assignments/port-numbers to get more detailed information). The services in the IANA list can use the port numbers in this range of 1,024 to 65, 535. To create this connection, you can choose one of the three constructor of the TCPCLIENT class:
1, public tclient () When using this constructor that does not have any parameters, the default communication port number 0 will be used with the default communication port number 0 when using this constructor that does not have any parameters. In this case, if the unit does not stop an IP address, it will not be possible to choose. The following statement exemplifies how to use the default constructor to create a new TCPCLIENT:
TcpClient TcpClientc = New TcpClient ();
2. Public TCPClient (IpendPoint) Create an instance object of TCPClient using this unit IpendPoint. The previous introduction, IpendPoint expands the network endpoint as the IP address and port number, which is used to specify the local network interface (IP address) and port number used when establishing a remote host connection, this constructing method is used This machine ipaddress and port provide room for selection. The following statement samples how to create an instance of the TCPClient class using local endpoints:
Iphostentry ipinfo = dns.gethostbyname ("www.tuha.net"); // host information ipaddresslist [] iplist = ipinfo.addresslist; // ip address array ipaddress ip = iPlist [0]; // Multi IP address is generally used The first IpendPoint Ipep = New IpendPoint (IP, 4088); // Get Network End Point Try {TcpClient TcpClienta = New TcpClient (iPlocalendPoint);} Catch (Exception E) {Console.writeline (E.TOSTRING ());} Here, you may be confused, the client is to create a connection, and the specified IP address and communication port number should be the remote server! In fact, this is true, using two configuration functions, you are only the TCPClient instance object with the IP address and the Bind of the port port, you need to explicitly specify the connection with the remote host, this can pass TCPClient The CONNECT method of the class is implemented, and the Connet method uses the specified hostname and port number to connect the client to the remote host:
1) Public void connect (iPndPoint); connect the client to the remote TCP host using the specified remote network endpoint.
Public Void Connect (ipaddress, int); connects 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 pointed out that the parameter iPndPoint network in all overloaded forms of the Connect method
Node, ipaddress, and DNS hostnames expressed as String, the PORT port indicated by INT refers to a remote server.
The following example statement uses the host default IP and PORT port number 0 to establish a connection with the remote host:
TCPCLIENT TCPCLIENT = New TCPCLIENT (); // Create a TCPClient object instance try {tcpclient.connect ("www.contoso.com", 11002); // Established connection} catch (Exception E) {Console.writeline (E.TOSTRING ));
3, public tclient (string, int); initializing new instances of the TCPCLIENT class and connecting to the specified port on the specified host. Different from the first two constructor, this constructor will automatically establish a connection, you no longer need to call the Connect method, where the String type parameter represents the DNS name of the remote host, such as: www.tuha.net.
The following example statement calls this method to connect to the host of the specified host name and port number:
Try {tcpclient tclientb = new tcpclient ("www.tuha.net", 4088);} catch (eXception e) {console.writeline (e.tostring ());} We said that the TCPClient class is created above Socket, A higher level of abstraction is provided in terms of TCP services, reflecting the transmission and acceptance of network data, is TCPClient's standard STREAM stream processing technology, making it more convenient to read and write data, while the .NET framework is responsible for providing richer The structure is to process the stream, run through the flow of flow in the entire .NET framework, which is more widely compatible, and constructs a general method on more general flow operation, making us no longer need to confuse the actual content of the file (HTML, XML or Other content), the application will use the consistent method (stream.write, stream.read) to send and receive data. In addition, the stream provides instant access to the data from the Internet download, and can start processing immediately when some data arrives, without waiting for the application to download the entire data set. These processing techniques are implemented through the NetWorkStream class in .NET. The NetWorkStream class contains in the system.net.sockets namespace of the .NET Framework, which provides basic data streams for network access. NetWorkStream implements standard .NET framework flow mechanisms that send and receive data over the network socket. NetworkStream supports synchronization and asynchronous access to network data streams. NetworkStream is inherited from Stream, which provides a set of methods and properties for easy network communication.
Like other inheritance of the abstract base stream Stream, the NetworkStream network stream can also be considered a data channel, which is equipped between the data source terminal (customer client) and the receiving end (service server), and the subsequent data read and Writings are made for this channel.
In the .NET framework, NetworkStream stream supports two aspects:
1, write flow. Writing is a data transmission from the data structure to stream.
2, read the stream. Read is data transfer from streaming to data structures (such as byte array).
Unlike ordinary streams, the network stream does not have a unified concept of the current location, so it does not support the search and random access to the data stream. The corresponding attribute canseek always returns false, while the Seek and Position methods will also trigger NotSupportedException.
Based on the application protocol on the socket, you can get the NetWorkStream network data stream in two ways:
1. Use the NetworkStream constructor: Public NetworkStream (Socket, FileAccess, Bool); (with overloaded method), use the specified access permission and the specified Socket to create a new instance of the NetWorkStream class, you are using you You need to create a socket object instance and establish a connection with the remote server via the socket.connect method, and then you can use this method to get the network traffic flow. Examples are as follows:
Socket S = New Socket (AddressFamily.internetwork, SocketType.Stream, protocoltype.tcp); // Create a client Socket object instance try {s.connect ("www.tuha.net", 4088); // Establish and Remote Host Connection} Catch (Exception E) {MessageBox.show ("Connection Error:" E.Message);} Try {NetworkStream Stream = New NetworkStream (S, FileAccess.Readwrite, false); // Net Get Network Transport} 2 , By tcpclient.getStream method: public networkStream etStream (); it returns the base network stream networkStream for transmitting and receiving data. GetStream creates an instance of a NetWorkStream class by using the base socket as its constructor parameters. You need to create a TCPClient object instance before use and establish a connection with the remote host. Examples are as follows:
TCPCLIENT TCPCLIENT = New TCPCLIENT (); // Create TCPClient object instance try {tcpclient.connect ("www.tuha.net", 4088); // Try connected to remote host} Catch (Exception E) {MessageBox.show (" Connection error: " E.Message);} try {networkStream stream = tcpclient.getStream (); // Get Network Transmission Stream} Catch (Exception E) {MessageBox.show (" TCPCLIENT Error: " E.MESSAGE); }
After getting the NetWorkStream network stream, you can use the standard stream reading method WRITE and READ to send and accept data.
The above is the technical information to implement client programming under the .NET, in order to provide these services to the client, we also need to prepare the corresponding server program, the previous "Visual C # .NET Network Program Development - Socket" Once mentioned, Socket is based on other network protocols, which can be developed for client development, or for server-to-server, more in the transmission level, and on the application protocol level, the client we construct built in the Socket class TCPClient replaces Socket; correspondingly, TCPListener built on Socket provides a higher concept-class TCP service, making us more easily writing server applications. It is because of this reason that the application layer protocols like FTP and HTTP are created on the basis of the TCPListener class.
TCPListener in .NET is used to monitor the incoming request on the TCP port, create the TCPListener object instance by binding the native IP address and the corresponding port (both should be consistent with the client's request), and start listening by the start method; When TCPListener detects that the client's connection, the AcceptTTCPClient method accepts the incoming connection request and creates a request, or the Acceptsocket method is accepted by the AcceptSocket method, depending on the client's different request, or to process the incoming connection request, or create a Socket to handle the request. Finally, you need to use STOP to turn off the socket used to listen to the incoming connection, you must also close any instances returned from Acceptsocket or AcceptTCPClient. This process is detailed as follows:
First, create a TCPListener object instance, which is implemented by the constructor of the TCPListener class: public tcplistener (port); // Specify the local port public tcplistener (iPadpoint) // Specify the native endpoint public tcplistener (iPadDress, port) //// Specify the native IP address and port
The parameters in the above methods are mentioned in the previous methods, and this is no longer detailed, and the only thing to remind is that these parameters are for the server host. The following example demonstrates an instance of creating 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 tcplistener = new TCPListener ipaddress, 4088); // Create a TCPListener object instance to listen to the user-end connection} catch (Exception E) {MessageBox.show ("TCPListener error:" E.MESSAGE);
Subsequently, you need to call the Start method to start listening:
Public void start ();
Second, when it is listened to a user-end connection, you need to accept the pending connection request, which is completed by calling one of the following two methods:
Public socket acceptsocket (); public tclient accepttcpclient ();
The previous method returns the Socket object that represents the client, which can then communicate with the remote computer through the Socket class; the latter method returns the TCPCPCPClient object that represents the client, and then use the TCPCLIENT.GETSTREAM method described above to get the basic network stream of TCPClient. NetworkStream, and write a read / write method with remote computer communication.
Finally, please remember to close the listener: public void stop ();
At the same time, close other connection examples: public void close ();
The following example reflects the above process:
Bool done = false; tcplistener listner = new tcplistener (13); // Create a TCPListener object instance (No. 13 port provides time service) listener.Start (); // Start listening while (! done) {// Enter infinite loop To listen to the user connection TcpClient client = listener.accepttcpclient (); // Soaled to create a client connection TCPClient NetworkStream ns = client.getStream (); // Get network transport stream Byte [] bytetime = encoding.ascii. Gettes (DateTime.now.tostring ()); // Pre-sent content (this is the server time) Convert to byte arrays to write the stream try {ns.write (bytetime, 0, bytetime.length); // Write the stream ns.close (); // Close the stream client.close (); // Close the client connection} catch (Exception E) {MessageBox.show ("Flow error:" E.Message)} Comprehensive application Knowledge, the following example implements a simple network communication - dual-machine interconnect, the application is compiled for the client and the server. The client creates a connection to the server, send a connection to the remote host to request the connection signal, and send a conversation content; the remote host receives the connection from the customer, send a confirmation of the connection to the client, and receives and displays the client's conversation content. On this basis, play your creativity, you can fully develop a chat room based on programming language (C #)! Client main source code:
Public void sendmeg () // Send information {TRY {
INT port = int32.parse ()); // Remote host port try {tcpclient = new tclient (TextBox1.text, port); // Create TCPCLIENT object instance} catch (exception le) {MessageBox. Show ("TCPCLIENT ERROR:" Le.Message);} string strdateline = datetime.now.toshortdateString () " DateTime.now.tolongTimeString (); // Get sending client time netstream = tclient.getStream ); // Get network stream sw = new streamwriter (NetStream); // Create textWriter, write characters in the stream String Words = TextBox4.text; // String content = strDateLine words; // To send content SW .Write (content); // write stream sw.close (); // Close the stream writer NetStream.close (); // Turn off the network stream TcpClient.close (); // Close client connection} catch Exception ex) {MessageBox.show ("Sending Message Failed!" EX.MESSAGE);} textbox4.text = ""; // Empty}
Server-side main source code: