Visual C # .NET Network Program Development - TCP

xiaoxiao2021-03-06  70

Author: Song Hua before a "Visual C # .Net web application development -Socket chapter," said: supports Http, Tcp and Udp classes make up the TCP / IP layer model (request response layer, application protocol layer, transport layer) Intermediate layer - Application Protocol layer, the class of the layer provides a higher level of abstraction than the bottom-level 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 When the word level protocol, you can use TCPCLIENT, UDPCLIENT and TCPLISTENER, instead of writing to the socket directly. 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 use one of the three constructor of the TCPClient class: 1. Public TCPCPClient () When using this constructor with any parameters, the default IP address will be used and will be used by default. Communication port number 0. 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 create new TCPCPClient: TcpClient tclientc = new tclient (); 2, public tclient (ipendPoint) uses native IpendPoint instance objects to create TCPClient. 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 a 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 generally uses the first IpendPoint Ipep = New IpendPoint (IP, 4088); // Get network endpoint try {tcpclient tcpclienta = new TcpClient (iPlocalendPoint);} catch Exception E) {Console.writeLine (E.TOString ());} You may feel confusion, the client is to create a connection, 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. The Connet method uses the specified hostname and port number to connect the client to the remote host: 1), public void connect (ipendPoint); 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 IpendPoint network end node in all overload forms of the Connect method, iPaddress, and DNS host names that are String and INT indicate that the telemators are remote servers. The following example statement uses the host default IP and PORT port number 0 to establish a connection with the remote host: tcpclient tclient = 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 (intend); initialize a new instance of the TCPClient class and connect 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 a host that specifies hostname and port number: try {tcpclient tclientb = new TcpClient ("www.tuha.net", 4088);} catch (exception e) {console.writeline (e. TSTRING ());} We said that TCPClient class creates higher levels of abstraction above the TCP service, reflecting the transmission and acceptance of network data, is TCPCLIENT uses standard Stream flow processing technology, Make it read and write data more convenient and intuitive, while the .NET framework is responsible for providing a richer structure to process streams, running throughout the stream in the entire .NET framework has a broader compatibility, constructing in a more general flow operation. General Methods Let us no longer need to confuse the actual content of the file (HTML, XML, or any 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. Figure 2, reading flow. Read is data transfer from streaming to data structures (such as byte array). Different from ordinary streaming stream is that 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 overload method), it uses the specified access Permissions and the specified Socket is authorized to create a new instance of the NetWorkStream class for the specified Socket. You need to create a socket object instance before use, and establish a connection with the remote server through the socket.connect method, and then you can use this method to get the network transport stream. .

Examples are as follows: socket s = new socket (addressfamily.internetwork, sockettype.internem, protocoltype.tcp); // Create a client socket object instance try {s.connect ("www.tuha.net", 4088); // Establishment Connection with the remote host} catch (Exception E) {MessageBox.show ("Connection error:" E.Message);} trystream (S, FileAccess.Readwrite, false); // Get network transmission Flow} 2, through the TCPClient.getStream method: public networkStream etStream (); it returns the basic 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 to connect to the remote host} catch (exception e) {messagebox.show ("connection error:" E.MESSAGE);} try {networkstream stream = tcpclient.getStream (); // Get network transport stream} catch (Exception E) {MessageBox.show ("TCPCLIENT Error:" E.MESSAGE); 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 construction method of the TCPListener class: public tcplistener (port); // Specify the local port public tcplistener (IpendPoint) // Specify the native endpoint public tcplistener Ipaddress, port) / / Specifies the parameters in the native IP address and above, mentioned previously, this is no longer detailed, the only thing to remind is that these parameters are for the server host. The following example demonstrates an instance of the 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 the listening: public void start (); Second, when it is listened to a user-end connection, you need to accept the hang-up request, which is completed by calling one of the following two methods: public Socket Acceptsocket (); public tclient accepttcpclient (); Previous method Returns the Socket object on behalf of the client, which can then communicate with the remote computer through the Socket class; the latter method returns the TCPCPClient object that represents the client, and then use the above introduction TCPClient.getStream method Gets the basic network stream of TCPClient, and communicates with the remote computer using the READ / WRITE method using the flow read / write method.

Finally, please remember to close the listener: public void stop (); simultaneously close other connection instances: public void close (); The following example reflects the above process: BOOL DONE = false; tcplistener Listener = New Tcplistener (13 ); // Create a TCPListener object instance (No.13 port provides time service) listener.Start (); // Start listening while (! Done) {// enters unlimited loop to listen to users TCPCPCPCLIENT Client = listener.accePttcpClient ); // Solver, create a client connection TcpClient networkStream ns = client.getStream (); // Get network transport stream Byte [] bytetime = encoding.ascii.getbytes (DateTime.now.tostring ()); / / Pre-sent content (this is the server time) Convert to byte an array to write the stream try {ns.write (bytetime, 0, bytetime.length); // write flow ns.close (); // Close CLIENT.CLOSE (); // Close Close Client Connection} Catch (Exception E) {MessageBox.show ("Flow error:" E.Message)} Comprehensively use the above knowledge, the following instance implements simple network communication - Double-machine interconnection, the application is compiled for the client and the server, respectively. 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.Pars (TextBox3.Text.tostring ()); // Remote Host Port Try {TcpClient = New Tclient (TextBox1.text, Port); // Create a TCPClient object instance} Catch (Exception le) {MessageBox.show ("TcpClient Error:" Le.MESSAGE); TolongTimeString (); // Get sending client time NetStream = tcpclient.getStream (); // Get network stream sw = new streamwriter (NetStream); // Create textWriter, write characters in the stream String Words = TextBox4.Text; // String content = strdateline words to be sent; // to send content sw.write (); // write stream sw.close (); // Close stream writer NetStream.close (); // Turn off the network stream TcpClient.close (); // Turn off the client connection} catch (exception ex) {messagebox.show ("Sending Message Failed!" EX.MESSAGE);} textbox4.text = ""; // Clear} Server-side main source code: public void startlisten () // User request {// receivemeg (); islinked = false; // connection flag try {int port = int32.parse (TextBox1.Text.toString )))); // Local standby port serverListener = new TCPListener (port); // Create a TCPListener object instance serverListener.Start (); // Start listening} catch (Exception ex) {MessageBox.show (" CAN't Start Server " EX.MESSAGE); Return;} islinked = true; while (true) // Enter the unlimited loop Waiting user-end connection {TRY {tcpclient = serverListener.accePttcpClient (); // Create a client connection object NetStream = tcpclient.getStream (); // Get network stream sr = new streamreader (netstream); // flow reader} catch (exception re) {messageBox.show (re.MESSAGE);} String buffer = " String received = ""; received = sr.readline (); // Read the line While (Received.Length! = 0) {Buffer = Received; buffer = "/ r / n"; // received = "" Received = sr.readline ();

转载请注明原文地址:https://www.9cbs.com/read-121274.html

New Post(0)