简体   繁体   English

C#TCP Server-Client:无法在无限循环中从客户端接收数据

[英]C# TCP Server-Client: can't receive data from the client in an infinite loop

Faced with the following problem. 面临以下问题。 Reads data from a text file. 从文本文件读取数据。 Every 40 milliseconds, the data is sent to the server. 每40毫秒,数据将发送到服务器。 Server must read the data into an infinite loop in a separate stream. 服务器必须将数据读取到单独流中的无限循环中。 But this is not happening. 但是,这没有发生。 What is wrong? 怎么了?

Client: 客户:

class Client
{ 
    private TcpClient _client;
    private Stream _stream;
    private Boolean _isConnected;
    private double[] _values;


    public Client(String ipAddress, int portNum)
    {
        _client = new TcpClient();
        _client.Connect(ipAddress, portNum);
    }


    public void SendValues(double[] values)
    {
        _values = values;
        HandleCommunication();
    }


    public void HandleCommunication()
    {
        _isConnected = true;
        _stream = _client.GetStream();

        var dataBytes = new List<byte>();

        foreach (double value in _values)
        {
            dataBytes.AddRange(BitConverter.GetBytes(value));

        }

        _client.SendBufferSize = _values.Length * sizeof(double);
        _stream.Write(dataBytes.ToArray(), 0, _client.SendBufferSize);
        Console.Write("Sending...");
        _stream.Flush();
    }

send data: 发送数据:

 public partial class MainWindow : Window
{
    private double[] values;
    private System.Timers.Timer timer = new System.Timers.Timer(40);
    Client _client = new Client("127.0.0.1", 55443);


    public MainWindow()
    {
        InitializeComponent();
        OpenSrcFile();

        timer.Elapsed += TimerOnElapsed;
        timer.Enabled = true;
    }


    private void TimerOnElapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("is sending...");
        _client.SendValues(values);
    }


    public void OpenSrcFile()
    {
        List<string> lines = File.ReadAllLines(@"file.txt").ToList();
        string r = lines[0];
        int sizeX = int.Parse(lines[1]);
        lines.RemoveRange(0, 2);
        values = GetValues(lines.ToArray());
    }


    private double[] GetValues(string[] lines)
    {
        return lines.Select(line => double.Parse(line.Replace(" ", ""), CultureInfo.InvariantCulture)).ToArray();
    }

Server: 服务器:

class Server
{
    private TcpListener _server;
    private Boolean _isRunning;

    public Server(int port)
    {
        _server = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
        _server.Start();

        _isRunning = true;
    }

    public double[] GetData()
    {

            // wait for client connection

            TcpClient client = _server.AcceptTcpClient();

            Console.WriteLine("Connected!");

            var stream = client.GetStream();

            byte[] buffer = new byte[256*sizeof (double)];


            stream.Read(buffer, 0, buffer.Length);

            double[] newValues = new double[buffer.Length/sizeof (double)];



            for (int i = 0; i < newValues.Length; i++)
            {
                newValues[i] = BitConverter.ToDouble(buffer, i*sizeof (double));
            }

            stream.Flush();

            return newValues;


    }


}

Receive data, but for some reason does not work 接收数据,但由于某些原因无法正常工作

public partial class MainWindow : Window
{
    private Thread _thread;
    private double[] _values;
    private Server _server = new Server(55443);

    public MainWindow()
    {
        InitializeComponent();
        InitializeThread();
    }


    private void InitializeThread()
    {
        _thread = new Thread(GetData);
        _thread.IsBackground = true;
        _thread.Start();
    }


    private void GetData()
    {
        while (true)
        {
            _values = _server.GetData();
            Console.WriteLine("...");
        }
    }

}

Okay, the client sends a byte array, this part is working correctly. 好的,客户端发送了一个字节数组,这部分工作正常。 Then we need to get this array of bytes into an infinite loop in a separate thread. 然后,我们需要将此字节数组放入单独线程中的无限循环中。 Like in this place: 喜欢在这个地方:

private void InitializeThread()
{
    _thread = new Thread(GetData);
    _thread.IsBackground = true;
    _thread.Start();
}


private void GetData()
{
    while (true)
    {
        _values = _server.GetData();
        Console.WriteLine("...");
    }
}

But somehow, the server receives a byte array once and nothing happens next. 但是以某种方式,服务器一次接收到一个字节数组,接下来什么也没有发生。 function GetData you can find in code 您可以在代码中找到的功能GetData

You put the loop in the wrong spot! 您将循环放在错误的位置!

Your client connects exactly once; 您的客户仅连接一次; which is correct. 哪个是对的。 However, in your GetData function you accept a new connection. 但是,在您的GetData函数中,您接受一个新连接。 Thus, after the first read, the loop calls GetData again, which blocks while waiting for a new connection, and nothing happens. 因此,在第一次读取之后,循环再次调用GetData ,该数据在等待连接时被阻塞,并且什么也没有发生。

Instead, you want to loop around the Accept call in the server class itself, and when you get a connection, start a "Read" thread for it (raise an event when you get data). 而是要在服务器类本身中循环Accept调用,并在获得连接时为其启动“读取”线程(获取数据时引发事件)。 There should be no looping in your main application for handling server operations. 主应用程序中不应存在用于处理服务器操作的循环。

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

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