c# - 异步套接字-与C#中的永久套接字的双工通信

标签 c# .net sockets asynchronous duplex

我正在尝试进行异步套接字通信,并希望服务器保留所有已连接套接字的列表,以便他可以向它们广播消息。

首先,我从msdn Asynchronous Socket Server中获取示例,并对其进行了一些改动,以使它们不会关闭套接字。 (只需删除.shutdown和.Close命令)

但是这样做似乎会使客户陷入“接收部分”。

这是我对msdn示例所做的更改:

客户:

仅更改了ReceiveCallback(),因此它处于无休止的接收循环中:

private static void ReceiveCallback(IAsyncResult ar)
{
    try
    {
        // Retrieve the state object and the client socket 
        // from the asynchronous state object.
        StateObject state = (StateObject)ar.AsyncState;
        Socket client = state.workSocket;

        // Read data from the remote device.
        int bytesRead = client.EndReceive(ar);

        if (bytesRead > 0)
        {
            // There might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

            // Get the rest of the data.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        else
        {
            // All the data has arrived; put it in response.
            if (state.sb.Length > 1)
            {
                response = state.sb.ToString();
                Console.WriteLine(state.sb.ToString());
            }
            // Signal that all bytes have been received.
            receiveDone.Set();

            // Get the rest of the data.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

服务器:
刚刚注释掉了关闭套接字的行:
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();

后来我计划保留一个套接字列表,以便我可以向其发送消息,但是这里已经失败了。

对于任何提示,我都很高兴,同时,我也想听听您对将这种习惯用于服务器最多可容纳100个客户端的服务器的意见,该服务器可以在2秒钟内发送请求。 (通信应该是双向的,以便客户端和服务器可以随时发送消息,而无需等待消息响应)。

谢谢你,晚上好
马丁

最佳答案

当套接字关闭时,EndReceive仅返回0。您的客户端永远不会设置receiveDone句柄,因为服务器从不关闭套接字。当接收到数据时或在连接终止时调用回调。

您需要检测消息的结尾(就像您链接的示例一样)。
例如。 (您链接的代码的修改后的版本)

content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1) {
     // All the data has been read from the 
     // client. Display it on the console.
     Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                 content.Length, content );
     // Echo the data back to the client.
     Send(handler, content);

     { // NEW 
         // Reset your state (persist any data that was from the next message?)      

         // Wait for the next message.
         handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
         new AsyncCallback(ReadCallback), state);
     }

 } else {
      // Not all data received. Get more.
      handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, 
      new AsyncCallback(ReadCallback), state);
}

关于c# - 异步套接字-与C#中的永久套接字的双工通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26003863/

相关文章:

c - TCC 和winsock.h

c# - C# 中的简单客户端服务器应用程序

c - 如何防止 socket() 系统调用返回文件描述符 0,1 或 2?

c# - 从 C# Web 应用程序调用 SSIS 并显示进度

c# - Linq 延迟操作

c# - 如何在 .NET WinForm 应用程序中显示 React App?

.net - 在 Windows 上生成 ActivityTracing 事件日志

c# - C#中的文件上传HTTP PUT

c# - 使用分组依据进行 LINQ 查询的帮助

.net - DataTable.Clear 和 DataTable.Rows.Clear 之间有区别吗?