C
C#3mo ago
naber top

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!");
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!");
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.
21 Replies
Jimmacle
Jimmacle3mo ago
Use Sockets to send and receive data over TCP - .NET
Learn how the Socket class exposes socket network communication functionality in .NET.
naber top
naber top3mo ago
why does the snippet use async
Jimmacle
Jimmacle3mo ago
because you generally should be using async with networking or any kind of IO in general it prevents blocking threads when waiting for IO operations
naber top
naber top3mo ago
await client.ConnectAsync(ipEndPoint); what does this do wait until connection then perform the while loop?
Jimmacle
Jimmacle3mo ago
it works the same as the synchronous Connect, it's just more efficient when you start doing multiple things at once
Jimmacle
Jimmacle3mo ago
Asynchronous programming in C# - C#
An overview of the C# language support for asynchronous programming using async, await, Task, and Task
naber top
naber top3mo ago
_ = await client.SendAsync(messageBytes, SocketFlags.None);
_ = await client.SendAsync(messageBytes, SocketFlags.None);
do I need to use "_" can't I just await client without declaring anything?
Jimmacle
Jimmacle3mo ago
that line doesn't declare anything, it's a way to explicitly show "i know this method returns something but i am ignoring it"
Jimmacle
Jimmacle3mo ago
Discards - unassigned discardable variables - C#
Describes C#'s support for discards, which are unassigned, discardable variables, and the ways in which discards can be used.
naber top
naber top3mo ago
what if I don't discard? would that cause me problems?
Jimmacle
Jimmacle3mo ago
no, it's a style choice it doesn't change how the code works if you do it or don't
naber top
naber top3mo ago
Any idea how can I implement usernames
Jimmacle
Jimmacle3mo ago
first you'll need to come up with a way to distinguish chat messages from "control" messages then have some kind of file/database on the server that associates users with their data
naber top
naber top3mo ago
would creating a class for users and a list containing that users work? or should I learn sql-like things
Jimmacle
Jimmacle3mo ago
you can start with something in C# and move to a proper database later if you want to learn it
naber top
naber top3mo ago
do I need to add await in SendAsync if I use it to create a method
Jimmacle
Jimmacle3mo ago
yes, async calls need to be awaited
naber top
naber top3mo ago
void SendMessage(string message)
{
var eom = "<|EOM|>";
message += eom;
byte[] messageBuffer = Encoding.UTF8.GetBytes($"{username}: {message}\n");
await clientSocket.SendAsync(messageBuffer);
Console.WriteLine($"Socket client sent message: \"{message.Replace(eom, "")}\"");
}
void SendMessage(string message)
{
var eom = "<|EOM|>";
message += eom;
byte[] messageBuffer = Encoding.UTF8.GetBytes($"{username}: {message}\n");
await clientSocket.SendAsync(messageBuffer);
Console.WriteLine($"Socket client sent message: \"{message.Replace(eom, "")}\"");
}
I receieve error when I add await Error CS4033 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. oh I added async before void and its fixed
Jimmacle
Jimmacle3mo ago
you should avoid async void at all costs if you need to await something, make it async Task
naber top
naber top3mo ago
why
Jimmacle
Jimmacle3mo ago
in this particular case, because you can't await it once you make something async you need to be async all the way up the call chain it also causes problems with handling exceptions