如何以 xamarin 形式与服务器进行正确的 TCP 客户端通信?

How to do proper TCP client-side communication with server in xamarin forms?

我正在尝试查看我的代码有什么问题,该代码使用 mvvm 架构以 xamarin 形式连接到服务器。客户端正在连接,但在使用 streamReader.readLine() 时出现以下错误:

System.IO.IOException: 无法从传输连接读取数据:在非阻塞套接字上操作会阻塞。

我正在为 TcpClient 实例使用 xamarin 表单和 System.Net.Sockets。我正在尝试与服务器进行同步通信以进行测试。

我有一个 TcpServer 程序被证明可以与其他设备一起工作。下面是一些进行通信的代码

连接属性页的ViewModel有如下代码:

     public ICommand TestConnectionCommand { get { return new 
    RelayCommand(sendMsg); } }
    public ICommand ConnectCommand { get; set; }

    public void sendMsg()
    {
        this.Response = new Response();
        this.EthernetConn.Port = 9091;
        this.EthernetConn.Ip = SelectedDevice.Ip;

        if (String.IsNullOrEmpty(EthernetConn.Ip))
        {
            Application.Current.MainPage.DisplayAlert(Languages.Error, Languages.IpValidation, Languages.Accept);
            return;
        }

        if (String.IsNullOrEmpty(EthernetConn.Timeout))
        {
            Application.Current.MainPage.DisplayAlert(Languages.Error, Languages.TimeoutValidation, Languages.Accept);
            return;
        }

        this.EthernetConn.Message = "TESTING\n";
        tcpService.Initialize(this.ethernetConn);
        this.Response.Message = tcpService.sendMessage(this.EthernetConn);

        if (this.Response.Message.Contains("FormatException"))
        {
            this.Response.IsSuccess = false;
            Application.Current.MainPage.DisplayAlert(Languages.Error, Languages.FormatValidation, Languages.Accept);
            this.IsRunning = false;
            this.IsEnabled = true;
            return;

        }
        else if (this.Response.Message.Contains("ArgumentNullException"))
        {
            this.Response.IsSuccess = false;
            Application.Current.MainPage.DisplayAlert(Languages.Error, this.Response.Message, Languages.Accept);
            this.IsRunning = false;
            this.IsEnabled = true;
            return;

        }
        else if (this.Response.Message.Contains("SocketException"))
        {
            this.Response.IsSuccess = false;
             Application.Current.MainPage.DisplayAlert(Languages.Error, this.Response.Message, Languages.Accept);
            this.IsRunning = false;
            this.IsEnabled = true;
            return;

        }
        else if (this.Response.Message.Contains("OK"))
        {
            this.Response.IsSuccess = true;
        }

        if (this.Response.IsSuccess)
        {
             Application.Current.MainPage.DisplayAlert(Languages.Success, Languages.ConnEstablished, Languages.Accept);
            this.IsRunning = false;
            this.IsEnabled = true;
        }
        else
        {
            Application.Current.MainPage.DisplayAlert(Languages.Error, Languages.ConnFailed, Languages.Accept);
            this.IsRunning = false;
            this.IsEnabled = true;
        }

    }

tcpService是TCPService的一个实例,它有建立连接的Initialize函数和sendMessage函数,其中出现错误的地方是:

    public void Initialize(EthernetConnection eth)
    {
        client.SendTimeout = Convert.ToInt16(eth.Timeout);
        client.ReceiveTimeout = Convert.ToInt16(eth.Timeout);
        client.Connect(eth.Ip, eth.Port);
    }


    public string sendMessage(EthernetConnection eth)
    {
        string response = String.Empty;
        try
        {
            if (!client.Connected)
            {
                return null;
            }
            var writer = new StreamWriter(client.GetStream());
            writer.WriteLine(eth.Message);

           //Here is where the problem seems to be:
            var reader = new StreamReader(client.GetStream());
            response = reader.ReadLine();

            return response;
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: {0}", e);
            return "ArgumentNullException: " + e;
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
            return "SocketException:: " + e;
        }
        catch (FormatException e)
        {
            Console.WriteLine("SocketException: {0}", e);
            return "FormatException: " + e;
        }

        }

我希望在 ReadLine 函数中读取数据。另外,如果它收到数据,我会在服务器端的控制台上进行一些打印,但我发现它没有。

有人能帮我看看我哪里错了吗?行之有效的解决方案也可以!

非常感谢!

无论何时使用 StreamWriter,您都需要 Flush() 流的内容。我将引用 MSDN,因为原因变得很清楚:

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

你可以这样使用它:

 var writer = new StreamWriter(client.GetStream());
 writer.AutoFlush = true;
 writer.WriteLine(eth.Message);
 writer.Flush();

您可以查看一个简单的演示: https://thuru.net/2012/01/07/simple-clientserver-in-c/