当前位置: 首页 > news >正文

python unity通讯数据解析2

python unity通讯数据解析_unity zmq-CSDN博客

Unity在服务器上

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

public class RecvPython : MonoBehaviour
{



    // Update is called once per frame
    void Update()
    {
        
    }

    private Thread serverThread;
    private TcpListener tcpListener;
    private bool isRunning = false;

    public int port = 65432; // 服务器端口

    void Start()
    {
        // 启动服务器
        StartServer();
    }

    void OnDestroy()
    {
        // 停止服务器
        StopServer();
    }

    void StartServer()
    {
        isRunning = true;
        serverThread = new Thread(ListenForClients);
        serverThread.Start();
        Debug.Log($"服务器已启动,正在监听端口 {port}...");
    }

    void StopServer()
    {
        isRunning = false;
        if (tcpListener != null)
        {
            tcpListener.Stop();
        }
        if (serverThread != null && serverThread.IsAlive)
        {
            serverThread.Join(); // 等待线程结束
        }
        Debug.Log("服务器已停止");
    }

    void ListenForClients()
    {
        try
        {
            // 创建 TCP 监听器
            tcpListener = new TcpListener(IPAddress.Any, port);
            tcpListener.Start();

            while (isRunning)
            {
                // 接受客户端连接
                TcpClient client = tcpListener.AcceptTcpClient();
                Debug.Log("客户端已连接!");

                // 为每个客户端创建一个线程
                Thread clientThread = new Thread(HandleClient);
                clientThread.Start(client);
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"服务器错误: {ex.Message}");
        }
    }

    void HandleClient(object obj)
    {
        TcpClient client = (TcpClient)obj;
        NetworkStream stream = client.GetStream();

        byte[] buffer = new byte[1024];
        int bytesRead;

        try
        {
            while (isRunning && (bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                // 接收客户端数据
                string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Debug.Log($"收到数据: {receivedData}");

                // 发送响应
                string response = "Hello from Unity Server";
                byte[] responseData = Encoding.UTF8.GetBytes(response);
                stream.Write(responseData, 0, responseData.Length);
                Debug.Log("已发送响应");
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"客户端处理错误: {ex.Message}");
        }
        finally
        {
            // 关闭连接
            client.Close();
            Debug.Log("客户端已断开连接");
        }
    }



}

Python 客服端

import socket


# 先运行unity
def tcp_client(host='127.0.0.1', port=65432):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
        client_socket.connect((host, port))
        client_socket.sendall(b"Hello from client")
        data = client_socket.recv(1024)
        print(f"收到响应: {data.decode()}")



tcp_client()

相关文章:

  • STAR Decomposition 一种针对极端事件的信号分解方法 论文精读加复现
  • 3.17学习总结
  • 【项目合集】智能语音小车-微信小程序控制
  • WebView2 nuget不能安装到unity项目中
  • 中间件 - 1.nats
  • Matlab GPU加速技术
  • 如何检查CMS建站系统的插件是否安全?
  • 使用 DrissionPage 实现网页内容自动化采集
  • Git Bisect 使用指南:高效定位引入 Bug 的提交
  • Qt之自定义界面组件 一
  • Jenkins 快讯
  • STM32G070CBT6读写FLASH中的数据
  • 浅谈Mysql数据库事务操作 用mybatis操作mysql事务 再在Springboot中使用Spring事务控制mysql事务回滚
  • ‌RTSPtoWeb, 一个将rtsp转换成webrtc的开源项目
  • 银河麒麟V10SP3Server中离线安装Docker引擎与docker-compose
  • 电池预测 | 第23讲 基于CNN-BiLSTM的锂电池剩余寿命预测,附带PPT视频讲解
  • GB9706.1-2020附件J绝缘路径参考
  • Redis系列:深入理解缓存穿透、缓存击穿、缓存雪崩及其解决方案
  • 如何用AI轻松制作完美PPT,节省时间又提升效率
  • 数据结构——查找
  • 马克思主义理论研究教学名师系列访谈|薛念文:回应时代课题,才能彰显强大生命力
  • 中青报:“爸妈替我在线相亲”,助力还是越界?
  • 女冰队长于柏巍,拒绝被年龄定义
  • 印度宣布即日起对所有巴基斯坦航班关闭领空
  • 金融监管总局修订发布《行政处罚办法》,7月1日起施行
  • 全文丨中华人民共和国民营经济促进法