我是靠谱客的博主 过时雪碧,这篇文章主要介绍Unity下的UDP客户端前言代码资源其他,现在分享给大家,希望可以做个参考。

Unity下简洁有效的UDP客户端

  • 前言
  • 代码
  • 资源
  • 其他
    • 中文乱码问题

前言

本来就想从网上找一个Unity的UDP客户端,百度上试了好多教程,问题百出,让人气不打一处来.
就几行代码的事情,浪费时间.

下面贴代码
ip和port改成服务器的
"connect"是连接时给服务器发送的
"HeartBeat"是心跳包

代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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); } }

资源

带UI的源码下载(free)
在这里插入图片描述

其他

中文乱码问题

ASCII 改成 UniCode

最后

以上就是过时雪碧最近收集整理的关于Unity下的UDP客户端前言代码资源其他的全部内容,更多相关Unity下内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部