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:
TcpClient client = new TcpClient(); client.Connect( serverAddress, serverPort );
The serverPort is an int 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 two, 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 four 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.
Client Server Interaction with Stream Socket Connections
|