Visual Basic.NET implementation TCP protocol [Date: 2004-11-17] [From: Aerial Developer Network] TCP protocol is an agreement in the transport layer in the TCP / IP protocol cluster, and the most important TCP / IP protocol cluster is most important One of the agreements. In TCP / IP protocol clusters, there is a protocol and TCP protocol very similar. This is the UDP protocol. When the UDP protocol is performed on the network, the sender only needs to know the IP address (or host name) and port of the recipient. No. You can send a UDP packet. The receiver can receive the UDP packet only if the receiver needs to know the port number corresponding to the sender. Data communication can be implemented in both sides of the transfer data, which results in a UDP protocol-based network application that cannot guarantee reliability, integrity, and security when transmitting data.
The TCP protocol is opposite, and the TCP protocol is a network protocol for connection, and providing reliable, complete, secure data transfer. It provides an agreement with a reliable byte service. The sender and the recipient must establish a connection before transmitting data through the TCP protocol, which is called "handshake". TCP applications in the network, such as calling in everyday life, before calling, first dialing, throws (like sending the TCP connection application, and waiting for TCP connection applications). Until the other party picks up the phone (the TCP connection of the sender and the receiver has been established), it can be called (transfer data). The main content of this article describes a simple way to implement TCP protocol network data transfer in Visual Basic .NET.
One. Introduction This article uses a class library that implements TCP protocol network applications:
The .NET Framework SDK provides a lot of class libraries to implement the TCP protocol or related protocols, this article selects five more typical, but also a relatively simple class, namely: TCPListener class, TCPCPCPCPCLIENT, NetWorkstream class, streamReader Class and Streamwriter class. TcpClient is mainly used to make a TCP connection application. TCPListener is primarily used to listen to the port number and receive the TCP connection request for the remote host. The NetWorkStream class is the basic data stream for implementing TCP data transmission, and the StreamReader class is to receive data from the network by operating the NetworkStream. The StreamWriter class is to transmit data to network by operating networkStream.
1. NetworkStream class:
The NetWorkStream class is mainly based on the basic data stream for network access. It is mainly a carrier of network data transmission, and provides synchronization, asynchronous mode to access network data streams. Although the NetworkStream class has a constructor, but in the actual situation, more is to initialize the NetWorkStream instance through the GetStream method of the TCPClient instance. Here is the GetStream method using the TCPCLIENT instance to initialize the NetWorkStream instance specific code:
After Dim As NetworkStreamtcpClient = New TcpClient ( "www.microsoft.com", 8000) 'propose a remote host on port 8000 TCP connection request nsStream = tcpClient.GetStream ()' tcpClient TcpClientDim nsStream As TCP connection is established, the data transmission network to obtain Basic data stream
In the example example described below, it is to utilize NetWorkStream as a carrier that transmits and receives data. This carrier is the StreamWriter class and the StreamReader class. Tables 01 and Table 02 are some common methods, attributes, and descriptions in the NetWorkStream class. Method Description BeginRead starts asynchronous readers' basic data stream. BeGinWrite starts to write to the underlying data stream asynchronously. Close Close the stream and select off the base socket. Endread ends asynchronously reading. Endwrite ends asynchronously. Flush refreshes the data in the stream. The read data is read from the stream. Seek sets the current position of the stream to a given value. SetLength Set the length of the stream. WRITE writes data into the stream.
Table 01: Methods and description thereof in the NetWorkStream class
Where "BeginRead", "endread", and "beginwrite", "endwrite" are two pairs of asynchronous methods, and the role is equivalent to "Read" and "Write" methods.
Property Description Canread gets reads in the current stream. Canseek gets streaming to support lookup. This property always returns false. CanWrite gets written in the current stream. DataAvailable Gets whether you can read data on the stream. The length of the available data is available on the LENGTH. Position Gets or sets the current location in the stream.
Table 02: NetWorkStream class Properties and their description
2. StreamReader class:
The StreamReader class enables read operations for the underlying data stream to implement data from the basic data. Table 03 is a common method of the StreamReader class and its description:
Method Description Close closes StreamReader and releases all system resources associated with the reader. DiscardBufferedData allows streamReader to discard its current data. PEEK returns the next available character but does not use it. The READ reads the next character or the next set of characters in the input stream. Readblock reads the maximum number of characters from the current stream and starts the data into the buffer from the index. Readline returns the data as a string from the current stream. ReadToeend reads the current from the current location of the stream to the end.
Table 03: Methods and descriptions in the NetWorkStream class
3. StreamWriter class:
The StreamWriter class is capable of implementing a write operation of the underlying data stream to implement the basic data flow to transmit data. Table 04 is a common method for the streamWriter class and its description:
Method Description Close Close the current streamWriter and the base stream. Flush cleans all buffers of the current writer and writes all buffer data to the base stream. Write is written to the underlying data stream. WriteLine is written to some of the data specified by the overload parameter, followed by the end of the character.
Table 04: Common methods of streamwriter class and its description
4.TcpClient class:
The TCPCLIENT class is primarily connected to TCP network services. TcpClient is a class building based on the Socket class, which provides TCP services at a higher abstraction. TCPClient provides a simple way to send and receive data over a network connection. Tables 05 and T T 36 are common methods, attributes, and descriptions of TCPCLIENT classes, respectively.
Method Description Close Close TCP Connection Connect uses the specified hostname and port number to connect the client to the TCP host getStream Returns the stream for transmitting and receiving data.
Table 05: TCPCLIENT common method
Property Description LingersTate Information Nodelay is a value of the Nodelay for the socket stay. This value is sent to the size of the ReceiveBuffersize receiving buffer after the transmission or reception buffer is not full. ReceiveTimeout Tclient is waiting for the time length of the time length for the reception data to receive data. SendBuffersize The size of the area SendTimeout after you start the sending operation, TCPCLIENT will wait for the time length table 06: TCPClient class is commonly used attributes
5.TCPListener Class:
The main role of the TCPListener class is to connect from the TCP network client, and the TCPListener class provides higher philosophy of TCP services based on the Socket class. You can use TCPListener to listen to the connection from the TCP client. An application layer protocol like FTP and HTTP is based on the TCPListener class. Table 7 and Table 8 are common methods, attributes, and descriptions of TCPListener class:
Method Description Acceptsocket accepts pending connection requests AcceptTCPCLIENT Accepting the pending connection request pending determines if there is a hang-up connection request START Start Listening Network Request STOP Close Listener Table 7: TCPListener class common method
Property Description LocalendPoint Gets the current TCPListener's foundation EndPoint Active gets a value, which indicates whether TCPListener is actively listening to the client connection server to get the base network Socket
Table 8: TCPListener class commonly used properties
two. Visual Basic .NET implements the architecture based on TCP protocol data transmitter:
The TCP protocol is implemented by the Visual Basic .NET described below is composed of two subroutines. It can also be seen as a server-side program and client program, where: The function of the server-side program is listening to the port number, receives the remote primary TCP connection request, and receives the text data from the remote host. Another subroutine, that is, the so-called client program, mainly implementing the TCP connection application to the remote host, and transmits text data to the remote host after the connection application is passed. Let's take a detailed introduction to the specific steps of the server-side programs transmitted by the TCP protocol network data transmitted in Visual Basic .NET.
three. The specific implementation steps for server-side programs:
The implementation key of the server-side program is listening to the port number, receives the TCP connection request for the remote host to obtain the basic data stream of network data transmission, and receive data through the base data stream. The receiving data is used in the READLINE method in the streamreader. Since the Readline method is a blocking method, in the following specific implementation step, the receiving data is completed in the created thread, specifically refer to the following implementation steps Eleventh and 12 steps. The following is the specific steps of the Visual Basic .NET implementation TCP protocol client program implementation:
1. Start Visual Studio .NET.
2. Select the menu [File] | [New] | [Project] to pop up the [New Project] dialog box.
3. Set the [Project Type] to [Visual Basic Project].
4. Set [Template] to [Windows Application].
5. Enter [Server-Director] in the [Name] text box.
6. Enter [E: /VS.NET Project] in the [Location] text box, then click the [OK] button, which generates a name "server side in the" E: /VS.NET project "directory. The program "folder and the project file named" Server-Dide Program "is created inside.
7. Switch the current window of Visual Studio .Net to the [Form1.vb (Design)] window, and drag into the following components from the [Windows Forms] tab in [Toolbox] to the Form1 Form, and Perform a corresponding action: a Label component. A STATUSBAR component. A ListBox component. A Button component, and after this Button component is dragged into the Form1 design form, double-click it, then the processing code corresponding to the Click event of this component is generated in the Form1.vb file.
8. Follow the table 05 to adjust the value of each component property in the form:
Component Type Component Name Properties Settings Form1 TEXT Server Dide Program Form1 MaximizeBox False Form1 FormBorderstyle FixedsingSingle Button1 TEXT Startup Service Button1 Flatstyle Flat Label Label1 Text Service has not launched Statusbar Statusbar1 Text No connection! Table 05: [Server Did Officer] Item Settings Numeric Table
And adjust the components in the design form according to the position and arrangement of each component in Figure 01:
Figure 01: Design interface of the server
9. Switch the current window of Visual Studio .Net to the code editing window of the Form1.vb, and add the following code to the top of the Form1.vb file, the following code Inform1.vb imports the names you want to use in the program. space:
Imports system.net.sockets' uses TCPListen IMPORTS System.thReading 'to use the thread imports system.io' to use the StreamReader class
10. Add the following code to create a variety of visual components in Form1.vb, the following code is to create instances and variables for global use:
Private iPort AS Integer = 8000 'Defines Listening Port Volume Private THREADREAD AS Thread' Creating Threads to listen to the port number, receive the information private tltcplisten as tcplistener 'listening port number private blistener as boolean = true' Setting the marking, Judging the Listening Status Private NSStream As NetworkStream 'Creating the received Basic Data Stream Private Srread As StreamReader' PRIVATE TCCLIENT AS TCPCLIENT from the Network Basic Data Stream
11. Add the following code after the InitializationComponent process in Form1.vb, the following code's role is to define the Listen procedure, the role of this process is to listen to the 8000 port number of the local machine, accept the TCP connection application of the network host, and receive from the establishment Text data sent by the remote host:
Private sub listen () TRY TLTCPLISTEN = New TCPListener (iPort) 'initializes the TCPListener instance tltcplisten.start () start listening Statusbar1.text = "Listening ..." tcclient = tltcplisten.accepttcpclient () TCP connection request nsstream = tcclient.getStream () Getting Network Basic Data Stream for sending, receiving data Srread = new streamreader (NSSTREAM) 'to initialize StreamReader instance statusbar1.text = "has established TCP Connection! "'Cycle Sales While Blistener Dim SMESSAGE AS STRING = srread.readLine ()' From the network underlying data stream (SMESSAGE =" STOP ") TLTCPLISTEN.STOP () closing the listening NSSTream. Close () srread.close () release resource statusbar1.text = "No connection!" THREADREAD.ABORT () 'Aborted Return Else' Decision is disconnected TCP connection control code DIM STIME AS STRING = DateTime.now.toshostTimeString () 'Getting time when receiving data ListBox1.Items.add (Stime "" SMESSAGE) end if End WhilecurityException MessageBox.show ("Listening Failed!", "Error") End Tryend Sub12. Replacing the processing code corresponding to the Click event of Button1 in Form1.vb with the following code, the following code function is to initialize and start the thread with the Listen procedure defined above, and receive the text data sent by the remote host of the TCP connection:
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click thThreadRead = New Thread (New ThreadStart (AddressOf Listen)) 'to Listen procedure to initialize thread instance thThreadRead.Start ()' start threads Button1.enabled = false label1.text = "Service has been started!" Label1.ForeColor = Color.Redend Sub
13. Replace the DISPOSE process in Form1.vb with the following code, the following code is to redefine the Dispose process, manually clear the resources used in the Dispose process, recycle garbage:
Protected Overloads Overrides Sub Dispose (ByVal disposing As Boolean) Try thThreadRead.Abort () 'abort threads tlTcpListen.Stop ()' close listening tcClient.Close () nsStream.Close () srRead.Close () 'release resources Catch End Try If DISPOSIING THEN INOT (Components Is Nothing) THENCOTS.DISPOSE () end if end if mybase.dispose (Disposing) End Sub14. After the above steps are executed correctly, the [server-side program] The full work of the project is completed. . After compiling, after generating an executable file, you will then describe the implementation steps of the client program.
four. Specific implementation steps for client-end programs:
The key to the client's port is to propose TCP connection applications to the remote host in the network, and after the application is passed, the basic data stream of transmitted data is obtained, and the text data is transmitted to the remote host by writing the underlying data stream. Since there is no blocking method in the client program, threads are not used in the program. For a specific implementation of a TCP connection request for a remote host, see the following steps; write the underlying data stream, and implement the method of transmitting text data to the remote host, see the following steps. The specific implementation steps for the following client programs:
1. Start Visual Studio .NET.
2. Select the menu [File] | [New] | [Project] to pop up the [New Project] dialog box.
3. Set the [Project Type] to [Visual Basic Project].
4. Set [Template] to [Windows Application].
5. Enter [Client Program] in the [Name] text box.
6. Enter [E: /VS.NET Project] in the [Position], then click the [OK] button, which generates a name "client in the" E: /VS.NET project "directory. The program "folder and the project file named" Client Program "is created inside.
7. Switch the current window of Visual Studio .Net to the [Form1.vb (Design)] window, and drag into the following components from the [Windows Forms] tab in [Toolbox] to the Form1 Form, and Perform a corresponding action:
Two label components. Two TextBox components. A STATUSBAR component. Two Button components, and after the two Button components are dragged into the Form1 design form, they double-click them, and the system will generate the processing code corresponding to the Click event of the two components in the Form1.vb file.
8. Follow the numerals of each component attribute in the form in Table 01:
Component Type Component Name property results Form Form1 Text client Form1 MaximizeBox False Form1 FormBorderStyle FixedSingle Button Button1 Text connection Button1 FlatStyle Flat Button2 Text sent Button2 FlatStyle Flat Label Label1 Text server IP address: Label2 Text Information: StatusBar StatusBar1 Text No connection! TextBox TextBox1 Text "TextBox1 Borderstyle Fixedsingle Textbox2 Text" TextBox2 Border FixedSingle
Table 06: [Client Program] Components Set Numeric Table
The components in the design form are adjusted in accordance with the position and arrangement of each component in Figure 02:
9. Switch the current window of Visual Studio .Net to the code editing window of the Form1.vb, and add the following code to the top of the Form1.vb file, the following code Inform1.vb imports the names you want to use in the program. space:
Imports system.net.sockets' Using TCPListen IMPORTS System.io 'uses the StreamWriter class imports system.net' uses the iPaddress class, iPhostentry class, etc.
10. Add the following code to create a variety of visual components in Form1.vb, the following code is to create instances and variables for global use:
Private swWriter As StreamWriter 'to spread transmission data to the network data base Private nsStream As NetworkStream' Create Private network based on a streaming data transmission tcpClient As TcpClient 'TCP connection to be made to a remote host application Private tcpConnect As Boolean = False through it' is defined The identifier is used to indicate whether the TCP connection is established.
11. Replace the processing code corresponding to the Click event of Button1 in Form1.vb with the following code, the following code feature is to propose TCP connection applications to the 8000 port number of the remote host, and initialize the basic data stream after connection is established:
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ipRemote As IPAddress Dim sHostName As String Dim tcpClient As TcpClient Try ipRemote = IPAddress.Parse (TextBox1.Text) Catch MessageBox.Show ( "Input IP address is not legal!", "Error Tip!") Return 'Judging the legality of the given IP address End try TCPCPCLIENT = New TCPClient (TextBox1.text, 8000)' Summary for the remote host 8000 ports TCP Connection Application NSSTREAM = TCPCLIENT.GETSTREAM () 'Through the application, and obtain network basic data stream of transmitting data SWRITER = New StreamWriter (NSSTREAM)' Using the obtained network basic data stream to initialize the streamwriter instance Button1.enabled = false button2.enabled = True TcpConnect = true statusbar1.text = "has been connected!" Catch MessageBox.show ("Unable to establish a connection with the remote host 8000 port!", "Error prompt!") Return End Tryend Sub
12. Replace the processing code corresponding to the Click event of Button2 in Form1.vb with the following code, the following code function is to write the underlying data stream to implement text data to the remote host:
Private Sub Button2_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click If (TextBox2.Text <> "") Then swWriter.WriteLine (TextBox2.Text) 'refresh the current data in the data stream swWriter .Flush () textBox2.text = "" "" Else MessageBox.show ("Send Information cannot be empty!", "Error Tip!") End ifnd sub13. Replace the DISPOSE process in Form1.vb with the following code, the following code It is redefined the Dispose process, determines whether the TCP connection is still established during the process, if the establishment transmits the control code to the remote host, disconnects, and manually clears the resources used, recycle garbage:
Protected Overloads Overrides Sub Dispose (Byval Disposing As Boolean) IF TCPConnect The Swwriter.writeline ("STOP") 'Send Control Code SWRITER.FLUSH ()' Refreshing Data in the current data NSStream.close () SWRITER.CLOSE () Clearing resource () end if if disposing the if not (Components is nothing) Then components.dispose () end if endiffs End Sub
14. This [client program] is completed. After the project is compiled correctly. You can choose to test any two computers in the LAN to test, a running client program, a running server server. After running the server-side program, click the [Start Service] button to start the service. After entering the IP address of the client program's [Server IP Address] text box, enter the IP address of the server-side program host, click the [Connection] button, establish a TCP connection with the server-side server that the boot service, at this time After entering the text message in the [Information] text box of the client program, click the [Send] button to transfer text information to the server side. Figures 03 and 04 are interfaces when the client program and the server-side program are running:
Figure 03: Running interface of the server-side program]
Figure 04: Running interface of [client program]
Fives. to sum up:
Although this article uses Visual Basic .NET to implement a simple TCP-based network application. However, the program is used in the program to achieve data transmission and reception through StreamWriter and StreamReader by operating this carrier. This implementation of the TCP protocol method is relatively simple, but it is not possible to avoid NetWorkStream as a network transmission, and receive a fatal defect of the data carrier, that is, NetworkStream can only transfer text-based data, if you want to transfer byte-based data, use This approach is hard. And sockets can compete for this job, but the socket can not only achieve various types of data transfer and reception on the network, but also the key to other application protocols in the network. If you want to truly become a master of network programming, you must master the use of Socket. Finally, I hope this article will open the door to write the network application and help you master more deeper network programming.