繁体   English   中英

C#TCP套接字服务器不响应客户端

[英]c# TCP socket server not responding to client

我有一个使用Mono的Ubuntu 12.04在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...");
        }
    }
}

服务器能够接收客户端请求,但是由于每次都无法连接,因此无法响应。 我在代码中丢失了某些内容吗?还是在这里工作?

您声明的附加Socket Sender是不必要的。 listenerSocket.Accept()接收到的handlerSocket已经是可用于与客户端通信的套接字。

当您接受使用服务器套接字的连接时,得到的是连接到客户端的套接字。 您不必创建新的套接字即可进行连接(实际上,您不能这样做)。 因此, handlerSocket创建和使用SenderhandlerSocket使用handlerSocket

handlerSocket.SendFile(_profileLocation);

暂无
暂无

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

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