c#TCP套接字服务器没有响应客户端

时间:2014-11-11 15:35:57

标签: c# sockets tcp mono

我使用Mono在Ubuntu 12.04下运行C#服务器,代码如下:

while (true)
{
    Console.WriteLine("Socket ready...");
    using (Socket handlerSocket = listenerSocket.Accept())
    {
        Console.WriteLine("New request...");
        BackgroundWorker newBackgroundWorker = new BackgroundWorker();
        byte[] buffer = new byte[1024];
        Console.WriteLine("Buffer allocated...");
        handlerSocket.Receive(buffer);
        //newBackgroundWorker.DoWork += (s, o) =>
        //{
        using (Socket Sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        {
            Console.WriteLine("Buffer received...");
            string request = Encoding.Unicode.GetString(buffer);
            Console.WriteLine("New request from : {0} /t Request : {1}", ((IPEndPoint)handlerSocket.RemoteEndPoint).Address.ToString(), request);
            if (request.Contains("$GetBattleList"))
            {
               //Chain of if's and else's continues
               //The following else if is the only case being tested

            else if (request.Contains("$GetZeroBasedProfile"))
            {
                Console.WriteLine("Sending profile...");
                Sender.Connect(handlerSocket.RemoteEndPoint); //Fails here due to not being able to reach the client application, throws a timeout exception
                Sender.SendFile(_profileLocation);
            }
            else Console.WriteLine("Invalid request. Ignoring...");
        }
    }
}

服务器能够接收客户端请求,但无法响应,因为它无法每次都连接。 我在代码中遗漏了什么或在这里有其他工作吗?

2 个答案:

答案 0 :(得分:3)

您需要声明的附加套接字Sender是不必要的。您从handlerSocket收到的listenerSocket.Accept()已经是您可以用来与客户进行通信的套接字。

答案 1 :(得分:1)

当您使用服务器套接字接受连接时,您得到的是连接到客户端的套接字。您不必创建要连接的新套接字(事实上,您不能)。因此,请使用Sender

,而不是创建和使用handlerSocket
handlerSocket.SendFile(_profileLocation);