问题
I'm messing around (for the first time) with Socket programming in C#, I'm making a Skype like application(Video call, IM, file share, screen share) and i have a couple of questions...
1) How should sockets truly work? On the client side I have a while loop which is effictively keeping the socket open, Is this correct? Or should i be closing the socket after each Send/Recieve (Im using BeginSend() and BeginRecieve()) and creating a new socket? interact() is called after the connection has been made. my code:
private static void interact()
{
try
{
while (true)
{
receive(client);
send(client);
}
}
catch (Exception e)
{
Logging.errorDisconnect(client, e);
}
}
2) How would you design a robust client/server application, by using BeginSend/BegingRecieve from System.Net.Sockets, or creating your own Task implementation?
3) Is there any good tutorials on Client/Server architecture for robust/scaleable applications? I've had a look at P2P but i'm not entirely sure its what i need.
Also, i'm trying to avoid 3rd party implementations so i can learn how it's done myself..
Thanks in advance..
回答1:
I assume you want to run a persistent connection and occasionally send commands to the remote side. This usually means that both sides must have a read loop running at all times to receive commands. Alternating between reading and writing makes sense for a request/reply model which you do not have here (because both sides can send requests and you might mistake an incoming request for an expected reply).
The loop is not keeping the socket alive. If you tell me why you were thinking that I can clarify. You decide the lifetime of the connection independently from any kind of "loop".
What kind of call style you want to use (sync, APM, TAP) does not affect how the socket behaves or what goes over the wire. You can choose freely. Sockets are super hard to get right, start with synchronous IO. Async IO is considerably harder and likely unnecessary here.
In general you should try hard to avoid using sockets because they are difficult and low-level. Try using some higher-level RPC mechanism such as WCF or HTTP. If you insist on a custom wire format protobuf is a good choice.
来源:https://stackoverflow.com/questions/33692502/socket-programming-design-questions