Unity3D使用UDPClient网络编程客户端程序

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


public class NewBehaviourScript : MonoBehaviour

// read Thread
Thread readThread;
// udpclient object
UdpClient client;
//server IP
public string IP = "127.0.0.1"; 
//server port number
public int port = 8080;
// UDP packet store
public string lastReceivedPacket = "";
public string allReceivedPackets = ""; // this one has to be cleaned up from time to time

// start from unity3d
void Start()
{
// create thread for reading UDP messages
readThread = new Thread(new ThreadStart(ReceiveData));
readThread.IsBackground = true;
readThread.Start();
}

// Unity Update Function
void Update()
{
// check button "q" to abort the read-thread
if (Input.GetKeyDown("q"))
stopThread();
}

// Unity Application Quit Function
void OnApplicationQuit()
{
stopThread();
}

// Stop reading UDP messages
private void stopThread()
{
if (readThread.IsAlive)
{
readThread.Abort();
}
client.Close();
}

// receive thread function
private void ReceiveData()
{
client = new UdpClient(10000);//创建的接收数据的端口号,服务器需要往该端口发送信息
client.Connect("127.0.0.1", 8080);//连接到服务器
IPEndPoint anyIP = null;
try
{
// Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");  
// client.Send(sendBytes, sendBytes.Length);


while (true)
{
// receive bytes


byte[] data = client.Receive(ref anyIP);

// encode UTF8-coded bytes to text format
string text = Encoding.UTF8.GetString(data);

// show received message
Debug.Log (text);

// store new massage as latest message
lastReceivedPacket = text;

// update received messages
allReceivedPackets = allReceivedPackets + text;

}


}
catch (Exception err)
{
Debug.Log((err.ToString());
}
}

// return the latest message
public string getLatestPacket()
{
allReceivedPackets = "";
return lastReceivedPacket;
}
}

你可能感兴趣的:(Unity3D使用UDPClient网络编程客户端程序)