Unity 多端游戏画面同步

客户端的代码

using UnityEngine;
using System.Collections;
//引入库
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.UI;
public class UdpClient : MonoBehaviour
{
    //以下默认都是私有的成员
    public static UdpClient Client;
    public bool isConnect=true;
    Socket socket; //目标socket
    EndPoint serverEnd; //服务端
    IPEndPoint ipEnd; //服务端端口
    string recvStr; //接收的字符串
    string sendStr; //发送的字符串
    byte[] recvData = new byte[1024]; //接收的数据,必须为字节
    byte[] sendData = new byte[1024]; //发送的数据,必须为字节
    int recvLen; //接收的数据长度
    Thread connectThread; //连接线程
    public InputField IpAddress;
    public InputField Port;
    public Canvas UI;
    //初始化
    void InitSocket(string IP,int port)
    {
        //定义连接的服务器ip和端口,可以是本机ip,局域网,互联网
        ipEnd = new IPEndPoint(IPAddress.Parse(IP),port);
        //定义套接字类型,在主线程中定义
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //定义服务端
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
        serverEnd = (EndPoint)sender;
        print("waiting for sending UDP dgram");
        SocketSend(Encoding.ASCII.GetBytes("hello"));
        UI.enabled = false;
    }

    public void SocketSend(byte[] image)
    {
        //清空发送缓存
        sendData = new byte[1024];
        //数据类型转换
        sendData = image;
        //发送给指定服务端
        socket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEnd);
    }
    //连接关闭
    void SocketQuit()
    {
        //关闭线程
        if (connectThread != null)
        {
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭socket
        if (socket != null)
            socket.Close();
    }
    public void Connect()
    {
        string IP = IpAddress.text;
        int port = int.Parse(Port.text);
        InitSocket(IP,port);
    }
    // Use this for initialization
    void Start()
    {
        Client = this;
       //InitSocket(); //在这里初始化
    }

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

    }

    void OnApplicationQuit()
    {
        SocketQuit();
    }
}

服务端代码

using UnityEngine;
using System.Collections;
//引入库
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class UdpServer : MonoBehaviour
{
    public static UdpServer Server;
    public static byte[] image;
    //以下默认都是私有的成员
    public string IpAdress;//本机的IP地址
    public int port;//端口
    Socket socket; //目标socket
    EndPoint clientEnd; //客户端
    IPEndPoint ipEnd; //侦听端口
    string recvStr; //接收的字符串
    string sendStr; //发送的字符串
    byte[] recvData = new byte[1024]; //接收的数据,必须为字节
    byte[] sendData = new byte[1024]; //发送的数据,必须为字节
    int recvLen; //接收的数据长度
    Thread connectThread; //连接线程
    float t = 0;
   
    void getIp()
    {
        IPHostEntry localhost = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress localaddr = localhost.AddressList[0];
        IpAdress= localaddr.ToString();
    }
    //初始化
    void Start()
    {
        Server = this;
        getIp();
        InitSocket(); //在这里初始化server
    }

    void InitSocket()
    {
        //定义侦听端口,侦听任何IP
        ipEnd = new IPEndPoint(IPAddress.Any, port);
        //定义套接字类型,在主线程中定义
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //服务端需要绑定ip
        socket.Bind(ipEnd);
        //定义客户端
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
        clientEnd = (EndPoint)sender;
        print("waiting for UDP dgram");
        //开启一个线程连接,必须的,否则主线程卡死
        connectThread = new Thread(new ThreadStart(SocketReceive));
        connectThread.Start();
    }

    public void SocketSend(byte [] byimg)
    {
        //清空发送缓存
        sendData = new byte[1024];
        //数据类型转换
        sendData =byimg;
        //发送给指定客户端
        socket.SendTo(sendData, sendData.Length, SocketFlags.None, clientEnd);
    }

    //服务器接收
    void SocketReceive()
    {
        //进入接收循环
        while (true)
        {
            //对data清零
            recvData = new byte[102400];
            //获取客户端,获取客户端数据,用引用给客户端赋值
            recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
            image = recvData;
            print("message from: " + clientEnd.ToString()); //打印客户端信息
            //输出接收到的数据
           // recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
            //print(recvStr);
            //将接收到的数据经过处理再发送出去
            //sendStr = "From Server: " + recvStr;
            //SocketSend(sendStr);
        }
    }

    //连接关闭
    void SocketQuit()
    {
        //关闭线程
        if (connectThread != null)
        {
            connectThread.Interrupt();
            connectThread.Abort();
        }
        //最后关闭socket
        if (socket != null)
            socket.Close();
        print("disconnect");
    }

    // Use this for initialization


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

    void OnApplicationQuit()
    {
        SocketQuit();
    }
}

通过Texture2D来获取手机视频画面 我这里通过多个摄像头来生产RenderTexture

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class tex : MonoBehaviour
{
    // Start is called before the first frame update
    public RenderTexture rt;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        byte[] by = getTexture2d(rt);
        try
        {   
                UdpClient.Client.SocketSend(by);
        }
        catch
        { 
        
        }
    }
    public byte[] getTexture2d(RenderTexture renderT)
    {
        if (renderT == null)
            return null;
        int width = renderT.width;
        int height = renderT.height;
        Texture2D tex2d = new Texture2D(width, height, TextureFormat.ARGB32, false);
        RenderTexture.active = renderT;
        tex2d.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        tex2d.Apply();
        byte[] b = tex2d.EncodeToPNG();
        Debug.Log(b.Length);
        Destroy(tex2d);
        return b;
    }
}

服务端读取renderTexture映射道Sprie上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Servertex : MonoBehaviour
{
    // Start is called before the first frame update
    public Sprite sp;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        try
        {
            sp.texture.LoadImage(UdpServer.image);
        }
        catch
        {

        }
    }
}

Unity 多端游戏画面同步_第1张图片

你可能感兴趣的:(Unity,C#,unity,游戏,游戏引擎)