Section 23.5. Establishing a Simple TCP Client Using Stream Sockets


23.5. Establishing a Simple TCP Client Using Stream Sockets

There are four steps to creating a simple TCP client. First, we create an object of class TcpClient (namespace System.Net.Sockets) to connect to the server. The connection is established by calling TcpClient method Connect. One overloaded version of this method takes two argumentsthe server's IP address and its port numberas in:

 Dim client As New TcpClient() client.Connect(serverAddress, serverPortNumber) 


The serverPortNumber is an Integer that represents the port number to which the server application is bound to listen for connection requests. The serverAddress can be either an IPAddress instance that encapsulates the server's IP address or a String that specifies the server's hostname or IP address. Method Connect also has an overloaded version to which you can pass an IPEndPoint object that represents an IP address/port number pair. TcpClient method Connect calls Socket method Connect to establish the connection. If the connection is successful, TcpClient method Connect returns a positive integer; otherwise, it returns 0.

In Step 2, the TcpClient uses its GetStream method to get a NetworkStream so that it can write to and read from the server. We then use the NetworkStream object to create a BinaryWriter and a BinaryReader that will be used to send information to and receive information from the server, respectively.

The third step is the processing phase, in which the client and the server communicate. In this phase of our example, the client uses BinaryWriter method Write and BinaryReader method ReadString to perform the appropriate communications. Using a process similar to that used by servers, a client can employ threads to prevent blocking of communication with other servers while processing data from one connection.

After the transmission is complete, Step 4 requires the client to close the connection by calling method Close on each of BinaryReader, BinaryWriter, NetworkStream and TcpClient. This closes each of the streams and the TcpClient's Socket to terminate the connection with the server. At this point, a new connection can be established through method Connect, as we have described.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net