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

时间:2015-07-10 21:14:21

标签: c# tcpclient streamreader streamwriter tcplistener

客户端

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());
        }


}
}

问题

事件跟踪:

  

开始!

     

您好我是鲍勃

     

您好我是鲍勃

     

(很多你好,我以后是bobs)

     

您好我是鲍勃

     

(你好,我刚刚停止了)

     

(约30秒)

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

在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());
       }
    }
}

答案 2 :(得分:0)

由于您正在创建一个且只有一个与服务器的连接,然后在客户端中不断发送消息,因此在处理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());
    }
}