TcpClient/TcpServer/Listener,服务器停止读取或客户端在 30 秒后停止

TcpClient/TcpServer/Listener, Server stops reading or client stops after 30 seconds

客户端

class Client
{
    public TcpClient client;
    public StreamWriter server;
    public ServerPlayer serverPlayer;
    public Player player;
    public void Connect(Player p)
    {
        player = p;
        serverPlayer = new ServerPlayer();
        client = new TcpClient(AddressFamily.InterNetwork);
        client.Connect("Don't wory my IPV4 Is Here", 8888);
        NetworkStream stream = client.GetStream();
        server = new StreamWriter(stream);
        Timer t = new Timer(Send, null, 0, 10);
    }
    public void Send(Object o)
    {
        server.WriteLine("Hello I am bob");
        server.Flush();

    }

}

服务器

class TcpServerConnection
{
    private static TcpListener tcpListener;
    static void Main(string[] args)
    {
        tcpListener = new TcpListener(IPAddress.Any, 8888);
        tcpListener.Start();
        Console.WriteLine("Server started.");

        while (true)
        {
            //blocks until a client has connected to the server
            TcpClient client = tcpListener.AcceptTcpClient();

            //create a thread to handle communication
            //with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }

    private static void HandleClientComm(object client)
    {
        while (true)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();
            StreamReader server = new StreamReader(clientStream);
            Console.WriteLine(server.ReadLine());
        }


}
}

问题

事件轨迹:

Started!

Hello I am bob

Hello I am bob

(Many Hello I am bobs later)

Hello I am bob

(Hello I am bobs just stopped)

(About 30 seconds)

不知道是因为客户端停止发送还是服务器停止接收,或者两者兼而有之!?但是一旦进入 运行 大约 30 秒,服务器就会停止获取发送信息。不会抛出任何错误,只是不会发送。

好的,在您的 ServerConnection 对象中,第一个 while 循环没问题。但是你的处理程序中的那个会导致一些问题试试这个:

private static void HandleClientComm(object client)
{
    TcpClient tcpClient = (TcpClient)client;
    NetworkStream clientStream = tcpClient.GetStream();
    using(var stream = new StreamReader(clientStream))
    {
       while (stream.Peek() >= 0) 
       {
           Console.WriteLine(server.ReadLine());
       }
    }
}

由于你是建立一个而且只有一个到Server的连接,然后在Client中不断的发送消息,相应地在Server程序中处理客户端消息时,你应该接受一个TcpClient然后循环读取消息,而不是接受一个 Tcplient 并在循环中读取一条消息。

private static void HandleClientComm(object client)
{
    TcpClient tcpClient = (TcpClient)client;
    NetworkStream clientStream = tcpClient.GetStream();
    StreamReader server = new StreamReader(clientStream);
    while (true)
    {
        Console.WriteLine(server.ReadLine());
    }
}

发现这是我的互联网。在我的 google-fu 之后。我将服务器的端口设置为 TCP 打开。在垃圾邮件进入随机端口后发现我的路由器变得可疑。 IP:IPV4 PORT:8888 SETTINGS:OPEN