我正在开发一个服务器应用程序,它将接收消息并做出响应。没有什么新东西。所以,实际上我正在关注 this answer 和 this post ,但我无法使用 AcceptAsync()
方法来触发 Completed
事件。在互联网上到处搜索,尝试了类似问题的解决方案,但似乎对我没有任何作用。
我也尝试从 server.Start()
调用 Task.Run()
,但没有成功。我知道服务器正在监听,因为我可以在 netstat -an
上看到它,如果我在 Listen()
之后中断,我也可以使用 telnet 进行连接。
据我所知,如果 AcceptAsync()
方法返回 true,它将引发 SocketAsyncEventArgs.Completed
事件,该事件又会再次调用 StartAccept()
方法并循环直到我强制退出。SocketAsyncEventArgs.Completed
也是正确的: http://prntscr.com/8l3x8p ,但仍然不起作用。
这是我的一段代码:
public class TTSServer
{
private Socket m_serverSocket;
private IPEndPoint m_serverEndPoint;
[DefaultValue(39454)]
public int Port { get; set; }
[DefaultValue(100)]
public int IncommingQueueSize { get; set; }
[DefaultValue(512)]
public int BufferSize { get; set; }
//Listeners to hold event when something happens.
public static void Main(string[] args)
{
TTSServer server = new TTSServer(39454, 100, 512);
server.Start();
}
public TTSServer(int port, int queueSize, int bufferSize)
{
Port = port;
IncommingQueueSize = queueSize;
BufferSize = bufferSize;
}
public void Start()
{
Console.WriteLine("Starting TTS Server (Port: {0}, QueueSize: {1}, BufferSize: {2})", Port, IncommingQueueSize, BufferSize);
m_serverEndPoint = new IPEndPoint(IPAddress.Any, Port);
m_serverSocket = new Socket(m_serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Binding ({0})", m_serverEndPoint.ToString());
m_serverSocket.Bind(m_serverEndPoint);
Console.WriteLine("Listening");
m_serverSocket.Listen(IncommingQueueSize);
StartAccept(null);
}
public void Stop()
{
}
/// <summary>
/// Receive a incomming connection attemp in an asynchronous way.
/// </summary>
/// <param name="socketEvent">If is null, a new object is created, else, it'll be used for cache friendly reason.</param>
private void StartAccept(SocketAsyncEventArgs socketEvent)
{
//If received reference points to null, let's create a new object.
if (socketEvent == null)
{
Console.WriteLine("Accepting new connections...");
socketEvent = new SocketAsyncEventArgs();
socketEvent.Completed += AcceptCompleted; //Add a callback on completed accept incomming connections attemp.
}
else
{
//Clear current incomming connection socket, so object may be reused.
socketEvent.AcceptSocket = null;
}
//If there is an incomming connection pending(pooled), this method will receive the connection in a async way (witch returns true)
//and will call SocketAsyncEventArgs.Completed callback when done.
//Else, it waits for a new connection, returns false, and don't won't SocketAsyncEventArgs.Completed callback when done, so we have to
//call it manually.
bool async = true;
//When I debug this code, async receive true from AcceptAsync.
async = m_serverSocket.AcceptAsync(socketEvent);
if (!async)
{
AcceptCompleted(this, socketEvent);
}
}
/// <summary>
/// Handles a incomming connection after it's fully received. This function will do the business logic for incomming connections and prepare
/// to receive data.
/// </summary>
/// <param name="sender">Object who posted this function</param>
/// <param name="socketEvent">Information of the incomming connection</param>
private void AcceptCompleted(object sender, SocketAsyncEventArgs socketEvent)
{
Connection connection = new Connection(this, socketEvent.AcceptSocket, BufferSize);
SocketAsyncEventArgs connectedSocketEvent = new SocketAsyncEventArgs();
connectedSocketEvent.UserToken = connection;
//Add a receive callback, to be called whenever the Receive function is finished.
connectedSocketEvent.Completed += FlushBuffer;
ReceiveData(connectedSocketEvent);
//Accept next incomming connection.
StartAccept(socketEvent);
}
不知道为什么,
AcceptCompleted
永远不会被触发,即使 AcceptAsync()
方法返回 true
。 最佳答案
似乎根本原因是默认缓冲:
假设不需要缓冲,禁用缓冲 seems to be a solution :
SocketAsyncEventArgs args = ...;
args.SetBuffer(null, 0, 0);
关于c# - 为什么 Socket.AcceptAsync 不触发 SocketAsyncEventArgs Completed 事件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32810722/