Multi Tcp服务器只能处理一个连接

时间:2018-01-23 14:08:37

标签: c# sockets tcp server connection

我正在处理可以处理许多客户端的tcp服务器。它用c#异步和回调编写。 所以我已经完成但是服务器只能处理一个连接......有些包含错误,但经过3天的搜索我不知道在哪里。我将粘贴代码。有趣:客户不会抛出任何错误。服务器仅显示一个连接的客户端。其他客户无法连接。

public class StateObject
{
    public Socket WorkSocket;
    public const int BufferSize = 32;
    public byte[] Buffer = new byte[BufferSize];
    public StringBuilder Sb = new StringBuilder();
}

internal class TcpServer
{
    public static Socket ServerSocket;
    public static List<SimClient> LbConnections = new List<SimClient>();

    public static async void StartTcpServerAsync()
    {
        try
        {
            await Task.Run(() =>
            {
                ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                LbConnections = new List<SimClient>();
                var serverIp = new IPEndPoint(IPAddress.Parse(Settings.Default.IPAddress), Settings.Default.Port);

                ServerSocket.Bind(serverIp);
                ServerSocket.Listen(0);
                InitServer.IsServerReady = true;

                ServerSocket.BeginAccept(AcceptCallback, ServerSocket);
            });
        }
        catch (Exception e)
        {
            AdvancedLogging.WriteLog(e.Message + "(" + e.InnerException + ")", 2);
            InitServer.IsServerReady = false;
        }
    }

    private static void AcceptCallback(IAsyncResult result)
    {
        var listener = (Socket)result.AsyncState;
        var handler = listener.EndAccept(result);

        var state = new StateObject();
        state.WorkSocket = handler;

        LbConnections.Add(new SimClient { State = state });
        handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
    }

    private static void ReceiveCallback(IAsyncResult result)
    {
        var state = (StateObject)result.AsyncState;
        var socket = state.WorkSocket;
        var received = socket.EndReceive(result);

        if (received <= 0)
        {
            socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
            return;
        }

        state.Sb.Append(Encoding.ASCII.GetString(
            state.Buffer, 0, received));

        var content = state.Sb.ToString();
        if (content.IndexOf("<EOF>", StringComparison.Ordinal) > -1)
        {
            DataHandler.HandleData(content.Substring(0, content.Length - 5), state);
            state.Sb.Clear();
            socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
        }
        else
        {
            socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您需要在致电BeginAccept

后致电handler.BeginReceive
private static void AcceptCallback(IAsyncResult result)
{
    var listener = (Socket)result.AsyncState;
    var handler = listener.EndAccept(result);

    var state = new StateObject();
    state.WorkSocket = handler;

    LbConnections.Add(new SimClient { State = state });
    handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
    ServerSocket.BeginAccept(AcceptCallback, ServerSocket);  // <<---
}

它的作用与BeginReceiveEndReceive相同。

在这种情况下,await Task.Run(() =>没用。你混合了两种不同的方法。 TPL和异步回调。

答案 1 :(得分:0)

Mhh如果我移动ServerSocket.BeginAccept(AcceptCallback,ServerSocket);在AcceptCallback中,任何时候都不会调用AcceptCallback。

EDIT 我不好意思。我需要调用ServerSocket.BeginAccept(AcceptCallback,listener); 谢谢:))