Wondering how this sample program can be made better. Specifically what exceptions should I expect to handle? Right now it's working as expected. I put a breakpoint after the statement:
int numBytesReadFromStream = stream.Read(bytes, 0, bytes.Length);
to check to see if the bytes variable had data in it and it did.
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
var localIP = IPAddress.Parse("10.10.10.117");
var listenerPort = 20000;
var senderPort = listenerPort + 2;
IPEndPoint listenerEndpoint = new IPEndPoint(localIP, listenerPort);
IPEndPoint senderEndpoint = new IPEndPoint(localIP, senderPort);
TcpListener tcpListener = new TcpListener(listenerEndpoint);
StarttcpListenerThread(tcpListener);
Thread.Sleep(300);
StartTCPSendingThread(listenerEndpoint, senderEndpoint);
while (true)
{
}
}
static void StarttcpListenerThread(TcpListener tcpListener)
{
tcpListener.Start();
Thread tcpListenerThread = new Thread(() =>
{
while (true)
{
try
{
byte[] bytes = new byte[1024];
TcpClient currentConnection = tcpListener.AcceptTcpClient();
NetworkStream stream = currentConnection.GetStream();
int numBytesReadFromStream = stream.Read(bytes, 0, bytes.Length);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
});
tcpListenerThread.Start();
}
static void StartTCPSendingThread(IPEndPoint listenerEndpoint, IPEndPoint senderEndpoint)
{
TcpClient tcpClient = new TcpClient(senderEndpoint);
tcpClient.Connect(listenerEndpoint);
Thread tcpSendingThread = new Thread(() =>
{
while (true)
{
try
{
tcpClient.Client.Send(new byte[] { 1, 2, 8 });
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
});
tcpSendingThread.Start();
}
}
}