C
C#8mo ago
koray bey

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
Jimmacle8mo ago
Use Sockets to send and receive data over TCP - .NET
Learn how the Socket class exposes socket network communication functionality in .NET.
koray bey
koray beyOP8mo ago
why does the snippet use async
Jimmacle
Jimmacle8mo 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
koray bey
koray beyOP8mo ago
await client.ConnectAsync(ipEndPoint); what does this do wait until connection then perform the while loop?
Jimmacle
Jimmacle8mo ago
it works the same as the synchronous Connect, it's just more efficient when you start doing multiple things at once
Jimmacle
Jimmacle8mo ago
Asynchronous programming in C# - C#
An overview of the C# language support for asynchronous programming using async, await, Task, and Task
koray bey
koray beyOP8mo 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
Jimmacle8mo 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
Jimmacle8mo 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.
koray bey
koray beyOP8mo ago
what if I don't discard? would that cause me problems?
Jimmacle
Jimmacle8mo ago
no, it's a style choice it doesn't change how the code works if you do it or don't
koray bey
koray beyOP7mo ago
Any idea how can I implement usernames
Jimmacle
Jimmacle7mo 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
koray bey
koray beyOP7mo ago
would creating a class for users and a list containing that users work? or should I learn sql-like things
Jimmacle
Jimmacle7mo ago
you can start with something in C# and move to a proper database later if you want to learn it
koray bey
koray beyOP7mo ago
do I need to add await in SendAsync if I use it to create a method
Jimmacle
Jimmacle7mo ago
yes, async calls need to be awaited
koray bey
koray beyOP7mo 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
Jimmacle7mo ago
you should avoid async void at all costs if you need to await something, make it async Task
koray bey
koray beyOP7mo ago
why
Jimmacle
Jimmacle7mo 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
Want results from more Discord servers?
Add your server