从TCP端口读取数据时出现问题 [英] Problem in reading data from a TCP port

查看:113
本文介绍了从TCP端口读取数据时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TCP服务器,它将侦听端口以进行输入查询,执行该命令并提供输出.我需要创建一个TCPClient应用程序,该应用程序将连接到端口,发送查询,读取输出并与端口断开连接.

实施客户:

I am having a TCP server, which will listen to a port for a input query, executes it and gives the output. I need to create a TCPClient application which will connect to the port, send the query, read the output and disconnects from the port.

Implementation of client:

private string SendMessage(string host, int port, string message)
{
    TcpClient client = new TcpClient(host, port);
    NetworkStream stream = client.GetStream();
            
    // Send the message
    byte[] data = Encoding.UTF8.GetBytes(message);
    stream.Write(data, 0, data.Length);
            
    // Mock thread.sleep
    while (!stream.DataAvailable) for (int i = 0; i < 1000; i++) ;
            
    // Read the data from the server
    StringBuilder sb = new StringBuilder();
    while (stream.DataAvailable)
    {
        data = new byte[client.ReceiveBufferSize];
        stream.Read(data, 0, data.Length);
        sb.Append(Encoding.UTF8.GetString(data));  
    }

    // Return the output
    return sb.ToString(); 
}


问题:服务器在处理查询并将数据写入端口上花费了一些时间.此外,也没有办法确定结果的终点.有时我的客户端应用程序无法完全读取数据(写入数据的速度可能比读取速度慢得多,或者在写入查询的输出时出现暂停)

限制条件:
1.服务器是第三方产品,我们无法更改其运行方式.
2.我们不应该在客户端应用程序中使用Thread.Sleep,因为它会降低性能.
3.我们不应该一次从端口读取一个字节,因为它会降低性能.

请给我任何完整读取数据的想法.有什么方法可以编写一个客户端类,该类异步读取数据?
欢迎使用任何指向其他文章的指针.


Problem: The server is taking a small time lag for processing the query and writing the data to the port. Also there is no way to identify the endpoint of the result. Sometimes my client application is not able to read the data completely (the data may be written much slower than the reading, or there is a pause while writing the outputs of the query)

Constraints:
1. The server is a third party product and we can''t change the way it operates.
2. We should not use Thread.Sleep in the client application as it degrades the performance.
3. We should not read one byte at a time from the port as it degrades the performance.

Please give me any idea for reading the data completely. Is there any way to write a client class, which reads the data asynchronously?
Any pointers to other articles are welcome.

推荐答案

请阅读本文

http://social.msdn.microsoft.com/Forums/zh/Vsexpressvcs/thread/25e8bb7b-ec3e-4977-abfb-6680bef7c78a [
Please read this article

http://social.msdn.microsoft.com/Forums/en/Vsexpressvcs/thread/25e8bb7b-ec3e-4977-abfb-6680bef7c78a[^]


这篇关于从TCP端口读取数据时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆