Socket Console App
Client
Server
How do I handle the possible exceptions and how do I communicate between.
21 Replies
have you looked at the resources in https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/sockets/socket-services ?
Use Sockets to send and receive data over TCP - .NET
Learn how the Socket class exposes socket network communication functionality in .NET.
why does the snippet use async
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
await client.ConnectAsync(ipEndPoint);
what does this do wait until connection then perform the while loop?
it works the same as the synchronous Connect, it's just more efficient when you start doing multiple things at once
Asynchronous programming in C# - C#
An overview of the C# language support for asynchronous programming using async, await, Task, and Task
do I need to use "_" can't I just await client without declaring anything?
that line doesn't declare anything, it's a way to explicitly show "i know this method returns something but i am ignoring it"
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.
what if I don't discard? would that cause me problems?
no, it's a style choice
it doesn't change how the code works if you do it or don't
Any idea how can I implement usernames
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
would creating a class for users and a list containing that users work?
or should I learn sql-like things
you can start with something in C# and move to a proper database later if you want to learn it
do I need to add await in SendAsync if I use it to create a method
yes, async calls need to be awaited
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
you should avoid async void at all costs
if you need to await something, make it
async Task
why
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