Socket Class Intro
In TcpClient
, TcpListener
, and UdpClient
(as well as many other classes) there is an underlying Socket
object. If you're looking for something simple to work with or want to get an application developed quickly, I'd recommend using those objects first. Though if you need more performance or want something that is much closer to the Berkeley/POSIX Socket API, then the Socket
class is what you'll want to use.
For this part of the series, I will present you with some C code (that uses the Berkeley Socket API) and then show you a C# port of that code. The C code is adapted from this Wikibooks article. I will not be showing you any usage of the asynchronous method right now. I want to start things off simple. We will cover async usage of the Socket
class in the next section.
The Application
The app is pretty simple. The server will open up a socket and wait for incoming connections. When a new client has connected, it will print some info to the terminal window and respond to the client with a short message. Then once it has been sent it will close the connection with the client. All of this will run over TCP.
I'm not going to do an explanation of what's' going on like I usually do. I think the code is very straightforward; there are comments sprinkled all over that should explain what each line does.
s
Compiling & running the C code for this section is completely optional. But make sure to read through it and try to understand a little bit of what's going on. If you want to compile and run the C code, you'll need to grab yourself a C compiler. I used clang (on Linux) when writing the C code, but it will also compile with something like gcc (on Windows via Cygwin). If you don't know or understand C that well (or the POSIX interface), don't worry about it.