PROWAREtech
.NET: TCP/IP Sockets API Tutorial - Page 3 - TCP Sockets
Using the TcpListener and TcpClient classes in C#.
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)
- Create a
TcpListener
object and specify the local address (if any) and port to listen on. - Call
Start()
method and the socket will listen for incoming connections. -
Repeat these steps:
- Call
AcceptTcpClient()
method. ATcpClient
object is returned. - Using the
TcpClient
NetworkStream
, use theRead()
andWrite()
methods to communicate with the client.
- Call
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
- A TCP connection can be opened using the
TcpClient
class constuctor or by using itsConnect()
methods. - 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());
}
}
}
Comment