zl程序教程

您现在的位置是:首页 >  其他

当前栏目

工程实践代码

代码 实践 工程
2023-09-27 14:27:29 时间

PlayerMovement

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
using UnityEngine.UI;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;
using System.Runtime.InteropServices;
using System;



public class PlayerMovement : MonoBehaviour
{
    //Player的运动信息
    private float m_WalkingSpeed = 1f;
    bool isWalking = false;
    Animator m_Animator;
    Rigidbody m_Rigidbody;
    Vector3 m_Movement;
 
    //滑轨小车
    CinemachineDollyCart m_Cart;

    //机器的运动信息
    public float Speed = 2f;
    public Text m_step;
    public Text m_distence;



    //Socket服务端的编写
    Socket socketSend;
    string recivedMsg="";
    int _port = 0;//端口号
    string _ip = "";//IP地址

    struct message//order是???
    {
        public string name;
        public string order;
        public string step;//改成时间
        public string dis;
        public string speed;
    }
    message mes = new message();
    
    
    private void Awake()
    {
        if (Display.displays.Length > 1)
        {
            Display.displays[1].Activate();
            Debug.Log(">1xianshiqi shuliang"+Display.displays.Length);
        }
        else if(Display.displays.Length == 1){
            Display.displays[0].Activate();
        }
       
        mes.name = "0";
        mes.order = "0";
        mes.step = "0";
        mes.dis = "0";
        mes.speed = "0.1";
        try
        {
            //服务器端开启监听
            int _port = 6001;
            string _ip = "127.0.0.1";
            //点击开始监听时 在服务端创建一个负责监听IP和端口号的Socket
            Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //获取IP地址
            IPAddress ip = IPAddress.Parse(_ip);
            //创建对象端口
            IPEndPoint point = new IPEndPoint(ip, _port);
            //绑定端口号
            socketWatch.Bind(point);
            Debug.Log("监听成功!");
            socketWatch.Listen(10);//设置监听,最大同时连接10台

            //创建监听线程
            Thread thread = new Thread(Listen);
            thread.IsBackground = true;
            thread.Start(socketWatch);//服务器启动监听
        }
        catch { }
    }

    
    /// <summary>
    ///监听等待PC端的连接,创建通信用的Socket
    /// </summary>
    void Listen(object o)
    {
        try
        {
            Socket socketWatch = o as Socket;
            while (true)//持续监听
            {
                //等待接收客户端连接,一但接收到请求就创建一个用于通信的Socket
                socketSend = socketWatch.Accept();
                //获得客户端的IP地址和端口号
                Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
                //开启一个新线程,执行接收消息方法
                //定义接收客户端消息的线程
                Thread r_thread = new Thread(Received);
                r_thread.IsBackground = true;
                r_thread.Start(socketSend);
            }
        }
        catch { }
    }


    /// <summary>
    /// 服务器端不停的接收客户端发来的消息
    ///监听消息
    /// </summary>
    /// <param name="o"></param>
    void Received(object o)
    {
        try
        {
            Socket socketSend = o as Socket;
            while (true)
            {
                //客户端连接服务器成功后,服务器接收客户端发送的消息
                //建立一个3M的缓冲区存放接收的数据
                byte[] buffer = new byte[1024 * 1024 * 3];
                //实际接收到的有效字节数 ,接收数据,返回数据长度
                int len = socketSend.Receive(buffer);
                if (len == 0)//客户端关闭,要退出循环
                {
                    break;
                }
                //接收客户端发送来的消息,把字节数据转成字符串
                string str = Encoding.UTF8.GetString(buffer, 0, len);
                Debug.Log("服务器打印:" + socketSend.RemoteEndPoint + ":" + str);
                //接收:xxx发送的消息:xxx
                Send("我收到了");
                recivedMsg = str;
                Debug.Log(recivedMsg);  
            }
        }
        catch
        {
        }
    }

    /// <summary>
    /// 服务器向客户端发送消息
    /// </summary>
    /// <param name="str"></param>
    void Send(string str)
    {
        //将发送的数据字符串转换为自己数组
        byte[] buffer = Encoding.UTF8.GetBytes(str);
        //发送到客户端
        socketSend.Send(buffer);
    }


    ///获取unity中的object和相应的组件
    void Start ()
    {
        m_Animator = GetComponent<Animator> ();
        m_Rigidbody = GetComponent<Rigidbody> ();
        m_Cart = GetComponent<CinemachineDollyCart>();
        m_step = transform.Find("Canvas/stepcount").GetComponent<Text>();
        m_distence = transform.Find("Canvas/distence").GetComponent<Text>();
    }
  //时刻判断Player的状态
    void Update ()
    {
       message mes= getmessage(recivedMsg);
        Debug.Log("mes order: " + mes.order);
        Debug.Log("mes step: " + mes.step);
        Debug.Log("mes dis: " + mes.dis);
        Debug.Log("mes speed: " + mes.speed);

        if (mes.order=="w"&&mes.name=="move")
        {
            isWalking = true;            
            m_Movement.Set(1f, 0f, 0f);
            
        }else if (mes.order == "s" && mes.name == "move")
        {
            isWalking = false;
        }
        m_WalkingSpeed = float.Parse(mes.speed);
        m_Animator.SetBool ("IsWalking", isWalking);
        m_Animator.speed = m_WalkingSpeed;
        if (isWalking)
        {
            m_Cart.m_Speed = m_WalkingSpeed;
        }else{
            m_Cart.m_Speed = 0;
        }
        m_step.text ="训练时长:"+ GetTime(float.Parse(mes.step));
        m_distence.text = "行走距离:" + mes.dis+"米";
    }
//获取时间,转换为时分秒格式
    string GetTime(float time)
    {
        float h = Mathf.FloorToInt(time / 3600f);
        float m = Mathf.FloorToInt(time / 60f - h * 60f);
        float s = Mathf.FloorToInt(time - m * 60f - h * 3600f);
        return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00");
    }


//获取输入的指令信息
    message getmessage(string rec)
    {
        Debug.Log("getmessage rec length"+rec.Length);
        int count = 0;
        string message_name = "";
        
        int pos_order = -1;
        bool is_one = true;
        if (rec.Length != 0)
        {
            pos_order = rec.IndexOf("@");
            //判断是否是单指令
            if (rec.IndexOf("@", pos_order + 1) != -1)
            {
                is_one = false;
            }
            //分别计算
            if (is_one)
            {
                return readmes(rec.Substring(1));
            }else if (!is_one)
            {
                count=rec.IndexOf("@", pos_order + 1);
                mes = readmes(rec.Substring(1, count-1));
                message_name = mes.name;
                mes = readmes(rec.Substring(count+1));
                //如果发送的命令是相同类型的粘包,则不变,若是move和data混合,则说明包含移动命令,需要保证name为move指令
                if (message_name != mes.name)
                {
                    mes.name = "move";
                }
                return mes;
            }
        }
        else
        {
            Debug.Log("empty");
        }

        return mes;
    }
//判断输入信息
   message readmes(string rec)
    {
        int pos_dou = -1;
        int pos_dou2 = -1;
        int pos_mao = -1;
        string sec_oder;

        pos_mao = rec.IndexOf(":");
        mes.name = rec.Substring(0, pos_mao);
      

        if (mes.name == "move")
        {
            mes.order = rec.Substring(pos_mao + 1);
        }
        else if (mes.name == "data")
        {
            pos_dou = rec.IndexOf(",");
            mes.step = rec.Substring(pos_mao + 1, pos_dou - pos_mao - 1);
            sec_oder = rec.Substring(pos_dou + 1);
            pos_dou2 = sec_oder.IndexOf(",")+pos_dou;
            mes.dis = rec.Substring(pos_dou + 1, pos_dou2 - pos_dou);
            mes.speed = rec.Substring(pos_dou2 + 2);
            Debug.Log("mes.steep in get message: " + mes.speed);
           
        }
        return mes;
    }

    //没调用????
    void OnAnimatorMove ()
    {
        m_Rigidbody.MovePosition (m_Rigidbody.position + m_Movement * m_Animator.deltaPosition.magnitude);
    }

}

 

 

WindowsShow

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.InteropServices;
//在拓展屏幕上全屏显示
public class WindowsShow : MonoBehaviour
{
    [HideInInspector]
    //导入设置窗口函数  
    //这里是引入 user32.dll 库, 这个库是windows系统自带的。
    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
    //导入当前活动窗口  
    [DllImport("user32.dll")]
    static extern IntPtr GetActiveWindow();
     //显示窗口
    const uint SWP_SHOWWINDOW = 0x0040;

    void Start()
    {
        //窗口置前
        SetWindowPos(GetActiveWindow(), -1, 1600, 0, 1920, 1080, SWP_SHOWWINDOW);
    }
}

客户端代码:

#python端作为客户端的代码

from socket import *

HOST = '127.0.0.1' # or 'localhost'
PORT = 6001
#定义接收客户端传过来消息的缓冲区大小
BUFSIZ =1024
ADDR = (HOST,PORT)
#创建Socket对象
tcpCliSock = socket(AF_INET,SOCK_STREAM)#网络协议,套接字的类型
#连接服务器端
tcpCliSock.connect(ADDR)
while True:
     data1 = input('>')
     #设置退出条件
     if not data1:
         break
     tcpCliSock.send(data1.encode())#发送数据
     data1 = tcpCliSock.recv(BUFSIZ)#接收服务器端返回的数据
     if not data1:
         break
     #解码
     print(data1.decode('utf-8'))
tcpCliSock.close()#关闭客户端链接