1. 程式人生 > >在unity中用UDP實現傳送訊息機制

在unity中用UDP實現傳送訊息機制

首先,用Unity新建兩個專案,然後一個寫Server,另一個寫Client。`using UnityEngine;
using System.Collections;
//引入庫
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class UdpServer : MonoBehaviour
{
//以下預設都是私有的成員
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; //連線執行緒

//初始化
void InitSocket()
{
    //定義偵聽埠,偵聽任何IP
    ipEnd = new IPEndPoint(IPAddress.Any, 8001);
    //定義套接字型別,在主執行緒中定義
    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();
}

void SocketSend(string sendStr)
{
    //清空傳送快取
    sendData = new byte[1024];
    //資料型別轉換
    sendData = Encoding.ASCII.GetBytes(sendStr);
    //傳送給指定客戶端
    socket.SendTo(sendData, sendData.Length, SocketFlags.None, clientEnd);
}

//伺服器接收
void SocketReceive()
{
    //進入接收迴圈
    while (true)
    {
        //對data清零
        recvData = new byte[1024];
        //獲取客戶端,獲取客戶端資料,用引用給客戶端賦值
        recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
        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
void Start()
{
    InitSocket(); //在這裡初始化server
}
void OnApplicationQuit()
{
    SocketQuit();
}

}
`上面程式碼是Server,然後把它繫結在相機上,

“`
using UnityEngine;
using System.Collections;
//引入庫
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class UdpClient : MonoBehaviour
{
string editString = “hello wolrd”; //編輯框文字

//以下預設都是私有的成員
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; //連線執行緒

//初始化
void InitSocket()
{
    //定義連線的伺服器ip和埠,可以是本機ip,區域網,網際網路
    ipEnd = new IPEndPoint(IPAddress.Parse("192.168.1.110"), 8001);
    //定義套接字型別,在主執行緒中定義
    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");

    //建立初始連線,這句非常重要,第一次連線初始化了serverEnd後面才能收到訊息
    SocketSend("hello");

    //開啟一個執行緒連線,必須的,否則主執行緒卡死
    connectThread = new Thread(new ThreadStart(SocketReceive));
    connectThread.Start();
}

void SocketSend(string sendStr)
{
    //清空傳送快取
    sendData = new byte[1024];
    //資料型別轉換
    sendData = Encoding.ASCII.GetBytes(sendStr);
    //傳送給指定服務端
    socket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEnd);
}

//伺服器接收
void SocketReceive()
{
    //進入接收迴圈
    while (true)
    {
        //對data清零
        recvData = new byte[1024];
        //獲取客戶端,獲取服務端端資料,用引用給服務端賦值,實際上服務端已經定義好並不需要賦值
        recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
        print("message from: " + serverEnd.ToString()); //列印服務端資訊
        //輸出接收到的資料
        recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
        print("我是客戶端,接收到伺服器的資料"+recvStr);
    }
}

//連線關閉
void SocketQuit()
{
    //關閉執行緒
    if (connectThread != null)
    {
        connectThread.Interrupt();
        connectThread.Abort();
    }
    //最後關閉socket
    if (socket != null)
        socket.Close();
}

// Use this for initialization
void Start()
{
    InitSocket(); //在這裡初始化
}

void OnGUI()
{
    editString = GUI.TextField(new Rect(10, 10, 100, 20), editString);
    if (GUI.Button(new Rect(10, 30, 60, 20), "send"))
        SocketSend(editString);
}

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

}

void OnApplicationQuit()
{
    SocketQuit();
}

}

“`這個是Client的,但是記得修改InitSocket()方法中的ip,改為你自己的Ip。