Sorry for the really broad question, but I’d love an answer.
For an idea I want one computer to start a server on a local network, and have another computer connect to this server in order to exchange data.
My question is how to do this?
As an added question, does someone have good tutorials on the System.net class reference?
One solution is to use Sockets. For a server socket, you create a socket and then call bind, listen and accept. This can be accomplished asynchronously or by just blocking the thread.
Now,
clientis the connection to the connected computer. Now you can use the Send method to actually send data between the two.The lengthbytes is used because the other client might not know how many bytes we are transferring for a “complete message”, so we simply tell it.
The client on the other hand uses the Connect method to connect to a running server, and Recive to get the bytes sent from the server.
Send and Receive work both ways by the way.
This is just scratching the surface though. There’s a lot of resources out there in the wild that goes over this, but perhaps this can be a stepping stone for you. You could for instance look into the
SocketAsyncEventArgsclass that is used for asynchronous communication, instead of blocking the thread when calling Receive.You should also look into sanitation of user provided data. Remember, the “length” is user provided since that is in the protocol that we just defined. We can’t tell the server to always send correct data, it might as well send -1 which will be bad when we try to allocate
new byte[length]. Sanitation, or validation, of data is necessary so the client doesn’t crash or does bad things on our own computer.