PROWAREtech

articles » current » dot-net » tutorial » sockets » page-3

.NET: TCP/IP Sockets API Tutorial - TCP Sockets

Using the TcpListener and TcpClient classes in C# - Page 3.

TCP Sockets

TCP is more robust than UDP and is better when sending large amounts of data. There are two .NET classes, TcpClient and TcpListener.

TcpListener (Server)

  1. Create a TcpListener object and specify the local address (if any) and port to listen on.
  2. Call Start() method and the socket will listen for incoming connections.
  3. Repeat these steps:
    • Call AcceptTcpClient() method. A TcpClient object is returned.
    • Using the TcpClient NetworkStream, use the Read() and Write() methods to communicate with the client.
using System;
using System.Net;
using System.Net.Sockets;

class TcpListenerServer
{
	static void Main()
	{
		WaitClient();
	}

	static private void WaitClient()
	{
		TcpListener listener = null;
		int port = 12345;

		try
		{
			listener = new TcpListener(IPAddress.Any, port);
			listener.Start();
			Console.WriteLine("Listening...");

			while (true)
			{
				try
				{
					using (TcpClient client = listener.AcceptTcpClient())
					{
						using (NetworkStream stream = client.GetStream())
						{
							Console.WriteLine("Connected to client: " + client.Client.RemoteEndPoint.ToString());

							byte[] bytes = new byte[1024];
							int read;
							int total = 0;
							while ((read = stream.Read(bytes, 0, bytes.Length)) > 0)
							{
								for (int i = 0; i < read / 2; i++) // reverse the message
								{
									byte tmp = bytes[i];
									bytes[i] = bytes[(read - 1) - i];
									bytes[(read - 1) - i] = tmp;
								}
								stream.Write(bytes, 0, read);
								total += read;
							}
							Console.WriteLine("{0} bytes sent to client\r\n", total);
						}
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message.ToString());
				}
			}
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message.ToString());
		}
	}
}

Following is the same server but in a multithreaded implementation. With multithreading, the server will be able to handle more client requests more responsively.

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

class TcpListenerServer
{
	static void Main()
	{
		WaitClient();
	}

	static private void WaitClient()
	{
		TcpListener listener = null;
		int port = 12345;

		try
		{
			listener = new TcpListener(IPAddress.Any, port);
			listener.Start();

			Console.WriteLine("Listening...");

			bool listening = true;
			while (listening)
			{
				if (listener.Pending())
				{
					var th1 = new Thread(ThreadMain); // create thread
					th1.Start(listener); // start thread passing listener as parameter
					Thread.Sleep(5); // pause main application thread for 5 milliseconds
				}
			}
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message.ToString());
		}
	}

	static void ThreadMain(object objListener)
	{
		TcpListener listener = (TcpListener)objListener;
		try
		{
			using (TcpClient client = listener.AcceptTcpClient())
			{
				Console.WriteLine("Connected to client: " + client.Client.RemoteEndPoint.ToString());

				using (NetworkStream stream = client.GetStream())
				{
					if(stream.DataAvailable)
					{
						byte[] bytes = new byte[1024];
						int read;
						int total = 0;
						while ((read = stream.Read(bytes, 0, bytes.Length)) > 0)
						{
							for (int i = 0; i < read / 2; i++) // reverse the message
							{
								byte tmp = bytes[i];
								bytes[i] = bytes[(read - 1) - i];
								bytes[(read - 1) - i] = tmp;
							}
							stream.Write(bytes, 0, read);
							total += read;
						}
						Console.WriteLine("{0} bytes sent to client\r\n", total);
					}
				}
			}
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message.ToString());
		}
	}
}

TcpClient

  1. A TCP connection can be opened using the TcpClient class constuctor or by using its Connect() methods.
  2. Like the file or other I/O stream, a connected TcpClient object can written to and read from.
using System;
using System.Text;
using System.Net.Sockets;

class TcpClientConnect
{
	static void Main()
	{
		ConnectToListener("9876543210 zyxwvutsrqponmlkjihgfedcba");
		while (true)
		{
			Console.Write("ENTER MESSAGE: ");
			string msg = Console.ReadLine();
			ConnectToListener(msg);
		}
	}

	static private void ConnectToListener(string appMessage)
	{
		string server = "localhost"; // 127.0.0.1
		int port = 12345;

		try
		{
			using (TcpClient client = new TcpClient(server, port))
			{
				using (NetworkStream stream = client.GetStream())
				{
					byte[] bytes = Encoding.ASCII.GetBytes(appMessage);

					stream.Write(bytes, 0, bytes.Length);

					int read; // bytes read
					int total; // total bytes read

					total = read = stream.Read(bytes, 0, bytes.Length);
					while (read > 0 && total < bytes.Length)
					{
						read = stream.Read(bytes, total, bytes.Length - total);
						total += read;
					}

					Console.WriteLine(Encoding.ASCII.GetString(bytes));
				}
			}
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.Message.ToString());
		}
	}
}
<<<[Page 3 of 3]>>>

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE