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

标签 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...");
        }
    }
}

服务器能够接收客户端请求,但是无法响应,因为它每次都无法连接。 我的代码中是否遗漏了某些内容,或者这里是否还有其他内容?

最佳答案

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

关于c# TCP 套接字服务器不响应客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26868533/

相关文章:

c# - 我如何跟踪对数据库所做的所有更改并将它们保存以供审查?

linux - UNIX 套接字魔法。推荐用于高性能应用?

java - Client SocketInputStream.close() 导致更多的资源消耗?

python - 在 Python 中通过 TCP 发送/接收多条消息

c# - 使用 SignalR 和 IProgress 接口(interface)的进度报告

c# - Entity Framework 核心 : Challenge Modeling Product Variants Database Design with Many to Many

python - 如何获得非阻塞套接字连接()?

wcf:是否有可能与 tcp 绑定(bind)和流式传输模式签订双工契约(Contract)?

.net - SocketAsyncEventArgs "pooled byte[]"样式是否有助于减少内存需求?

c# - Entity Framework 导航属性上的 .Skip().Take() 正在我的 SQL Server 上执行 SELECT *