繁体   English   中英

AsyncTCP C# - arduino/unity 通信

[英]AsyncTCP C# - arduino/unity communication

过去几周我一直在使用 tcp 协议使用以下代码将数据包从 arduino 发送到统一:

using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class TCPConnection : MonoBehaviour
{
    public string IP_Seat = "192.168.137.161";  
    public int port = 34197;
    #region private members     
    private TcpClient socketConnection;
    private Thread clientReceiveThread;
    public float a, b, c, vel;
    public float test = 0.0f;
    #endregion
    // Use this for initialization  
    void Awake()
    {
        ConnectToTcpServer();
    }
    
    /// <summary>   
    /// Setup socket connection.    
    /// </summary>  
    private void ConnectToTcpServer()
    {
        try
        {
            clientReceiveThread = new Thread(new ThreadStart(ListenForData));
            clientReceiveThread.IsBackground = true;
            clientReceiveThread.Start();
        }
        catch (Exception e)
        {
            Debug.Log("On client connect exception " + e);
        }
    }
    /// <summary>   
    /// Runs in background clientReceiveThread; Listens for incomming data.     
    /// </summary>     
    private void ListenForData()
    {
        var aold = 0.0f;
        var bold = 0.0f;
        var cold = 0.0f;
        var velold = 0.0f;
        try
        {
            socketConnection = new TcpClient(IP_Seat, port);
            //cketConnection.ConnectAsync(IP_Seat, port);  // non si connette
            //socketConnection.Client.Blocking = false;
            //socketConnection.Client.ConnectAsync(IP_Seat,port);
            Byte[] bytes = new Byte[16];
            while (socketConnection.Connected)
            {
                // Get a stream object for reading              
                using (NetworkStream stream = socketConnection.GetStream())
                {
                    int length;
                    // Read incomming stream into byte arrary.                  
                    while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        //Debug.Log("I'm receiving Data");
                        if (length == 16)
                        {
                            //Debug.Log("I'm receiving len 16 and I like it");
                            var incommingData = new byte[length];
                            var A = new Byte[4];
                            var B = new Byte[4];
                            var C = new Byte[4];
                            var VEL = new Byte[4];

                            Array.Copy(bytes, 0, incommingData, 0, length);
                            // Convert byte array to string message.                        
                            string serverMessage = Encoding.ASCII.GetString(incommingData);
                             Array.Copy(bytes, 0, A, 0, 4);
                             Array.Copy(bytes, 4, B, 0, 4);
                             Array.Copy(bytes, 8, C, 0, 4);
                             Array.Copy(bytes, 12, VEL, 0, 4);



                            a = BitConverter.ToSingle(A, 0) < 0 ? BitConverter.ToSingle(A, 0) : aold;
                            b = BitConverter.ToSingle(B, 0) < 0 ? BitConverter.ToSingle(B, 0) : bold;
                            c = BitConverter.ToSingle(C, 0) < 0 ? BitConverter.ToSingle(C, 0) : cold;
                            vel = BitConverter.ToSingle(VEL, 0); //< 0 ? BitConverter.ToSingle(C, 0) : 0;

                            //Debug.Log("server message received as: " + serverMessage +a +" "+b + " " + c + " " + vel);

                            aold = a;
                            bold = b;
                            cold = c;
                            velold = vel;

                        }
                        else {
                            //evitare che bilancia aspetti ack di tcp
                        }
                    }

                }
            }
        }
        catch (SocketException socketException)
        {
            Debug.Log("Socket exception: " + socketException);
        }
    }

}

现在我遇到了阻塞问题:我想对 TCP 使用异步方法,但tcpClient.ConnectAsync但它返回一个 SocketEXception,我不知道为什么。

arduino 在 16 字节数据包中发送 4 个浮点数,其中 98-99% 正确到达,但缺少 1-2% 会导致系统阻塞和不良行为(因为我正在对设备进行编程,所以我不需要延迟等待确认或数据包)

我怎样才能使这个sokcet异步?

正如@jdweng 已经说过的:TCP 只是一个未定义的 stream 数据,您需要实施相应的协议来了解消息何时结束(完全接收)以及何时开始新消息。

现在,在您的情况下,您似乎已经知道您正好有16个字节。

不是NetworkStream.Read的另一个参数,它是

int offset -> The location in buffer to begin storing the data to.

你想要做的是等到缓冲区实际上是满的

var receivedBytes = 0;
while (receivedBytes < bytes.Length)
{
    receivedBytes +=  stream.Read(bytes, receivedBytes, bytes.Length - receivedBytes);
}

// Use bytes

暂无
暂无

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

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