Arduino 与 Unity3D TCP通信

 一、通过传输流的方式

#include 

#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()
{

}
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);
        }
    }

    /// 
    /// 接收数据
    /// 
    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();
        }
    }
}

 二、通过传输流的方式

#include 

#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);
  }
}
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 sendMsgQueue = new Queue();

    //用于处理分包时,缓存的字节数组和字节数组长度
    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();
    }
}
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.Instance.Connect("192.168.50.49", 80);


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

}

你可能感兴趣的:(tcp/ip,网络协议,c#,开发语言)