前言
本来就想从网上找一个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;
// Start is called before the first frame update
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){
// this is what had been passed into BeginReceive as the second parameter:
UdpClient socket = result.AsyncState as UdpClient;
// points towards whoever had sent the message:
IPEndPoint source = new IPEndPoint(0, 0);
// get the actual message and fill out the source:
byte[] message = socket.EndReceive(result, ref source);
// do what you'd like with `message` here:
string returnData = Encoding.ASCII.GetString(message);
Debug.Log("Got this: " + returnData);
// schedule the next receive operation once reading is done:
socket.BeginReceive(new AsyncCallback(OnReceived), socket);
}
void HeartBeat(){
Byte[] sendBytes = Encoding.ASCII.GetBytes("heartbeat");
udp.Send(sendBytes, sendBytes.Length);
}
}
资源
其他
中文乱码问题
ASCII 改成 UniCode