前言
本来就想从网上找一个Unity的UDP客户端,百度上试了好多教程,问题百出,让人气不打一处来. 就几行代码的事情,浪费时间.
下面贴代码 ip和port改成服务器的 "connect"是连接时给服务器发送的 "HeartBeat"是心跳包
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
public class Network : MonoBehaviour
{
public UdpClient udp;
void Start()
{
udp = new UdpClient();
udp.Connect(ip,port);
Byte[] sendBytes = Encoding.ASCII.GetBytes("connect");
udp.Send(sendBytes, sendBytes.Length);
udp.BeginReceive(new AsyncCallback(OnReceived), udp);
InvokeRepeating("HeartBeat", 1, 1);
}
void OnDestroy(){
udp.Dispose();
}
void OnReceived(IAsyncResult result){
UdpClient socket = result.AsyncState as UdpClient;
IPEndPoint source = new IPEndPoint(0, 0);
byte[] message = socket.EndReceive(result, ref source);
string returnData = Encoding.ASCII.GetString(message);
Debug.Log("Got this: " + returnData);
socket.BeginReceive(new AsyncCallback(OnReceived), socket);
}
void HeartBeat(){
Byte[] sendBytes = Encoding.ASCII.GetBytes("heartbeat");
udp.Send(sendBytes, sendBytes.Length);
}
}
资源
带UI的源码下载(free)
其他
中文乱码问题
ASCII 改成 UniCode
|