Arduino 与 Unity3D TCP通信

一、通过传输流的方式

cs 复制代码
#include <WiFi.h>

#define LED_PIN 5
const char * ssid = "Daschow2021";
const char * password = "daschow2021";
void setup() {
  Serial.begin(9600);

  //连接WiFi
  WiFi.begin(ssid,password);

  Serial.print("正在连接Wifi");
  //检测是否连接成功
  while (WiFi.status()!=WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println("连接成功");
  Serial.print("IP 地址:");
  Serial.println(WiFi.localIP());

  //通过LED 反馈Wifi 连接状态
  pinMode(LED_PIN,OUTPUT);

  digitalWrite(LED_PIN,HIGH);
  delay(100);
  digitalWrite(LED_PIN,LOW);
  delay(100);

  digitalWrite(LED_PIN,HIGH);
  delay(1500);
  digitalWrite(LED_PIN,LOW);
}

void loop()
{

}
cs 复制代码
using UnityEngine;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
    private TcpClient client;
    private StreamReader reader;
    private StreamWriter writer;
    private Thread clientThread;

    public Button btnA;
    public Button btnB;

    public string serverIPAddress;
    public int serverPort;

    void Start()
    {
        ConnectToServer();

        btnA.onClick.AddListener(() => {
            sendMessage("a");
        });
        btnB.onClick.AddListener(() => {
            sendMessage("b");
        });
    }

    private void Update()
    {
        print(client.Connected);
    }

    void ConnectToServer()
    {
        try
        {
            client = new TcpClient();
            client.Connect(serverIPAddress, serverPort);
            Debug.Log("Connected to Arduino server");

            btnA.interactable = true;
            btnB.interactable = true;

            NetworkStream stream = client.GetStream();
            reader = new StreamReader(stream);
            writer = new StreamWriter(stream);

            clientThread = new Thread(new ThreadStart(ReceiveMessages));
            clientThread.Start();
        }
        catch (System.Exception e)
        {
            Debug.Log("Connection error: " + e.Message);
        }
    }

    /// <summary>
    /// 接收数据
    /// </summary>
    void ReceiveMessages()
    {
        try
        {
            while (client.Connected)
            {
                string message = reader.ReadLine();
                if (message != null)
                {
                    // 处理接收到的消息
                    handleMessage(message);
                }
            }
        }
        //异常断开连接
        catch (System.Exception e)
        {
            Debug.Log("Read/write error: " + e.Message);
        }
    }

    void sendMessage(string message)
    {
        try
        {
            writer.WriteLine(message);
            writer.Flush(); // 清空缓冲区,确保消息被发送
        }
        catch (System.Exception e)
        {
            Debug.Log("Read/write error: " + e.Message);
        }
    }

    void handleMessage(string message)
    {
        Debug.Log("Message received: " + message);
        // 在这里添加逻辑来处理接收到的消息
    }

    void OnDestroy()
    {
        if (client != null)
        {
            clientThread.Abort();
            writer.Close();
            reader.Close();
            client.Close();
        }
    }
}

二、通过传输流的方式

bash 复制代码
#include <WiFi.h>

#define LED_PIN 5

const char* ssid = "大西洲01";        // Wi-Fi网络名称
const char* password = "Foresight2022NB";    // Wi-Fi网络密码

WiFiServer server(80);    // 创建一个Wi-Fi服务器对象,监听端口80

const size_t bufferSize = 64;  // 缓冲区大小
char buffer[bufferSize];  // 声明和初始化缓冲区

void handleMessage(const char* message);  // 声明handleMessage函数

void setup() {
  pinMode(LED_PIN, OUTPUT);

  Serial.begin(115200);
  while (!Serial) {}  // 等待串口连接

  // 连接到Wi-Fi网络
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }

  // 打印IP地址
  Serial.println(WiFi.localIP());

  // 开始监听客户端连接
  server.begin();
}

void loop() {
  WiFiClient client = server.available();

  if (client) {
    while (client.connected()) {
      // 检查是否有可用数据
      if (client.available() > 0) {
        // 获取可用数据字节数
        size_t availableBytes = client.available();

        // 限制每次读取的字节数,避免缓冲区溢出
        size_t bytesToRead = min(availableBytes, bufferSize - 1);

        // 读取客户端发送的二进制数据
        size_t len = client.readBytes(buffer, bytesToRead);
        buffer[len] = '\0'; // 在字符串末尾添加终止符

        // 处理接收到的消息
        handleMessage(buffer);

        // 发送响应给客户端
        client.println("Data received");
        client.flush();

        delay(10);
      }
    }

    // 断开客户端连接
    client.stop();
  }
}

void handleMessage(const char* message) {
  // 在这里添加逻辑来处理接收到的字符串数据
  // 根据需要解析和处理收到的数据
  // 以下是一个简单的示例,假设收到的数据指令是控制LED开关

  if (strcmp(message, "a") == 0) {
    digitalWrite(LED_PIN, HIGH);
  } else if (strcmp(message, "b") == 0) {
    digitalWrite(LED_PIN, LOW);
  }
}
cs 复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class NetMgr : MonoBehaviour
{
    private static NetMgr instance;
    public static NetMgr Instance => instance;

    //客户端Socket
    private Socket socket;

    //用于发送消息队列 公共容器 主线程往里面放
    //private Queue<string> sendMsgQueue = new Queue<string>();

    //用于处理分包时,缓存的字节数组和字节数组长度
    private byte[] cacheBytes = new byte[1024 * 1024];
    private int cacheNum = 0;

    //是否连接
    private bool isConnected = false;

    private int SEND_HEART_MSG_TIME = 2;

    private void Awake()
    {
        instance = this;
        DontDestroyOnLoad(gameObject);
    }

    public void Connect(string ip, int port)
    {
        //避免多次连接
        if (isConnected) return;
        if (socket == null)
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //连接服务端
        IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip), port);

        try
        {
            print("服务器连接成功");
            socket.Connect(ipPoint);
            isConnected = true;

            开启发送线程
            //ThreadPool.QueueUserWorkItem(SendMsg);

        }
        catch (SocketException s)
        {
            if (s.ErrorCode == 10061)
                print("服务器拒绝连接");
            else
                print("连接失败" + s.ErrorCode + s.Message);
        }
    }

    //发送消息
    public void Send(string str) 
    {
        //sendMsgQueue.Enqueue(str);
        socket.Send(Encoding.UTF8.GetBytes(str));
    }

    //private void SendMsg(object state)
    //{
    //    while (isConnected)
    //    {
    //        if (sendMsgQueue.Count > 0)
    //        {
    //            string str = sendMsgQueue.Dequeue();
    //            print("Send:" + str);
    //            socket.Send(Encoding.UTF8.GetBytes(str));
    //        }
    //    }
    //}

    public void Close()
    {
        if (socket != null)
        {
            print("客户端主动断开连接");
            socket.Shutdown(SocketShutdown.Both);
            socket.Disconnect(false);
            socket.Close();
            socket = null;
            isConnected = false;
        }
    }

    private void OnDestroy()
    {
        Close();
    }
}
cs 复制代码
using UnityEngine;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using UnityEngine.UI;
using Unity.VisualScripting;

public class Test : MonoBehaviour
{
    public Button btnA;
    public Button btnB;
    private void Start()
    {
        if (NetMgr.Instance == null)
        {
            GameObject obj = new GameObject("Net");
            obj.AddComponent<NetMgr>();
        }
        NetMgr.Instance.Connect("192.168.50.49", 80);


        btnA.onClick.AddListener(() => {
            NetMgr.Instance.Send("a");
        });
        btnB.onClick.AddListener(() => {
            NetMgr.Instance.Send("b");
        });
    }

}
相关推荐
西猫雷婶7 分钟前
python学opencv|读取图像(二十一)使用cv2.circle()绘制圆形进阶
开发语言·python·opencv
kiiila8 分钟前
【Qt】对象树(生命周期管理)和字符集(cout打印乱码问题)
开发语言·qt
小_太_阳33 分钟前
Scala_【2】变量和数据类型
开发语言·后端·scala·intellij-idea
直裾36 分钟前
scala借阅图书保存记录(三)
开发语言·后端·scala
唐 城1 小时前
curl 放弃对 Hyper Rust HTTP 后端的支持
开发语言·http·rust
可喜~可乐1 小时前
C# WPF开发
microsoft·c#·wpf
码银3 小时前
【python】银行客户流失预测预处理部分,独热编码·标签编码·数据离散化处理·数据筛选·数据分割
开发语言·python
从善若水3 小时前
【2024】Merry Christmas!一起用Rust绘制一颗圣诞树吧
开发语言·后端·rust
2401_858286114 小时前
115.【C语言】数据结构之排序(希尔排序)
c语言·开发语言·数据结构·算法·排序算法
Jelena技术达人4 小时前
Java爬虫获取1688关键字 item_search接口返回值详细解析
java·开发语言·爬虫