Chat Client/Server Part 3: The Connection Class
If you have not read Part 1 and Part 2 of this network tutorial series, please do so now. The code in this post will build upon code from those posts.
The Connection Class: Beginning Network Code
We are going to get into the fun part of the network code in this part of the series. This post will teach you how to use TcpClient to send and receive data over the network. TcpClient is a class in Microsoft Dot Net which instantiates a TCP connection and can send and receive data in the form of byte arrays.
Step 1: Create our connection class. Right-click on our Chat class library and add a new class. Call that class “Connection”. This class will use our Packet class to send and receive data.
Step 2: Include the correct using statements. We need to include certain dot net classes to make our coding job easier. Add these using statements to the top of Connection.cs.
1 2 3 | using System; using System.Net.Sockets; using System.Net; |
The TcpClient class we are going to use is included by using these statements. This will make our coding easier since we don’t have to fully qualify each time we use the TcpClient class.
Step 3: Instantiate our TcpClient object. Inside of your Connection class, add the following line of code which will create our TcpClient class. By creating one here, it will be instantiated with our Connection object and always be available.
1 2 3 | public class Connection { TcpClient c = new TcpClient(); |
We now have a client object named “c” to work with in our network code.
Step 4: Constructors. Let’s create a couple of constructors for our connection class. One constructor should take a TcpClient object as a parameter, so that it can accept one that’s already created. Another constructor should just take a server to connect to and the port to connect to, and open the connection.
1 2 3 4 5 6 7 8 9 | public Connection(TcpClient client) { c = client; } public Connection(string server, int port) { c.Connect(server, port); } |
As you can see from the second constructor, opening a TCP connection to a given server with a given port is very easy to do. The call to Connect is a “blocking” operation, which as you should remember from Part 1 of this series means it will wait until the connection has been created successfully before continuing with any further code.
If the connection fails for any reason, an exception will be thrown. Any client code written using the Connection class should be able to handle that exception. As a matter of fact, every function in this class could possibly throw an exception, so your client code should always wrap network calls in a try/catch statement.
Follow Dave on Twitter