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

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


http://www.kler.cn/a/588046.html

相关文章:

  • WindowsPE文件格式入门01.PE头
  • [Windows] OfficeScrubber_13--office卸载清理工具
  • 【JavaEE】快速上手JSON:构建高效 Java 后端数据桥梁,开启交互新篇,以 @RequestBody 为引的探索之旅
  • 类和对象C++ (未完:对象特征)
  • linux - 基础IO之操作与文件描述符全解析:从C语言到系统调用底层实现
  • python爬虫Scrapy(5)之增量式
  • 生物角度分析
  • PHP语言的死锁
  • GBase8c 删除备机
  • 【Java 优选算法】分治 - 快速排序
  • 基于redis实现会话保持
  • Chat-Driven Business:灵活交互的新范式
  • python面向对象:封装的编程案例
  • 使用easyexcel实现单元格样式设置和下拉框设置
  • coze ai assistant Task 3
  • 【Django】【vue】设计一个评论模块
  • 【人工智能基础2】Tramsformer架构、自然语言处理基础、计算机视觉总结
  • 数字人本地部署之llama-本地推理模型
  • Skema:AI 驱动的方案到 BIM 加速工具,重塑早期设计工作流
  • superset部署记录