简体   繁体   English

如何使用C#中的套接字异步回复客户端?

[英]How do I reply asynchronously to a client using sockets in C#?

I have basically implemented this asynchronous server socket example (and the corresponding client). 我基本上已经实现了这个异步服务器套接字示例 (以及相应的客户端)。 Using it, I can respond to the client if I follow the example exactly, ie, if the call to Send() the response is in the ReadCallback() method. 使用它,如果我完全遵循示例,便可以响应客户端,即,如果对Send()的调用响应是在ReadCallback()方法中。

If, however, I try and send a response outside of here, ie, in a callback that I've attached to my message processing routine (running in a different thread), I get this error, saying the Socket is not connected. 但是,如果我尝试在此处之外发送响应,即在我附加到消息处理例程的回调中(在另一个线程中运行),则会收到错误,表示未连接Socket。 If I try and send a response somewhere else in the Server code, say in the while(true) loop that's listening to incoming connections, I get the same error. 如果我尝试在Server代码中的其他位置发送响应,例如在监听传入连接的while(true)循环中说,则会遇到相同的错误。

Am I missing something fundamental here? 我在这里缺少基本的东西吗?

Edit: 编辑:

Ok, so I read Two-way communication in socket programming using C , and I now think , according to that answer, that I have to modify the example I linked to so that I reply to the server on the socket returned by the accept process. 好的,所以我阅读了使用C进行套接字编程中的双向通信,现在我认为 ,根据该答案,我必须修改链接到的示例,以便在accept进程返回的套接字上回复服务器。 My goal is to be able to call Send() outside of the receive callback, say from Main() , after the client and server are connected. 我的目标是在客户端和服务器连接之后能够在接收回调之外(例如从Main()调用Send()

Please can someone suggest how I modify the example to achieve what I want? 请有人建议我如何修改示例以实现我想要的吗? I'm getting thoroughly confused about this, and don't want to create a separate stream if I don't need to (which according to the question I posted, I don't need to...). 我对此感到非常困惑,如果不需要,我不想创建单独的流(根据我发布的问题,我不需要...)。

If you want to keep the connection open then would need to persist the handler variable as that is the open socket connection. 如果要保持连接打开,则需要保留handler变量,因为这是打开的套接字连接。 Then whenever you want to send that connection a message you retrieve its socket and send. 然后,每当要发送该连接消息时,便会检索其套接字并发送。

Also, you obviously wouldn't call Shutdown() and Close() on the handler variable. 同样,您显然不会在handler变量上调用Shutdown()和Close()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM