Socket Console App

Client
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

string url = "tcp://6.tcp.eu.ngrok.io:";
Uri serverUri = new Uri(url);
string hostname = serverUri.Host;
IPAddress serverIP = Dns.GetHostEntry(hostname).AddressList[0];
ushort port;
do
{
    Console.Write("Enter port: ");
    if (ushort.TryParse(Console.ReadLine(), out port))
    {
        Debug.WriteLine("Successfully parsed");
        break;
    }
    else
    {
        Debug.WriteLine("Couldn't parse");
    }
    
} while (true);

Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

clientSocket.Connect(new IPEndPoint(serverIP, port));
Console.WriteLine("Connected!");


Server
using System.Diagnostics;
using System.Text;
using System.Net.Sockets;
using System.Net;


ushort port;

do
{
    Console.Write("Enter a port to listen: ");
    if (ushort.TryParse(Console.ReadLine(), out port))
    {
        Debug.WriteLine("Successfully parsed.");
        break;
    }
    else
    {
        Debug.WriteLine("Couldn't parse");
    }
} while (true);



Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

listener.Bind(new IPEndPoint(IPAddress.Any, port));

listener.Listen(10);

Console.WriteLine("Server started on port: " + port);

Socket clientSocket = listener.Accept();

Console.WriteLine("Client connected!");




How do I handle the possible exceptions and how do I communicate between.
Was this page helpful?