Unity实现Udp服务端的基本功能
在之前的博客中我写了关于简单实现Udp通信客户端的Demo,在实际项目中,我们有时候也要写Udp服务端的功能,以便于接收客户端发送过来的信号。在这篇博客中我简要介绍下Udp服务端的实现方法。
步骤
1.为了能够方便实现动态修改Udp服务端Ip和端口号功能,在这里首先加一个读取配置文件的功能,首先在工程中新建一个StreamingAssets文件夹,在里面新建一个Config.txt文件,切记要将其保存为UTF-8文件,如下图所示:
2.在Config.txt中输入如下内容,确定UdpServer和IP和端口号,以及客户端的端口号,如下图所示:
3.完成ComfigTest.cs脚本,将该脚本挂载到场景中的物体上,脚本代码如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
public class ConfigTest : MonoBehaviour
{
private string configPath;
public Dictionary<string, Dictionary<string, string>> dic;
// Use this for initialization
void Awake ()
{
//读取配置文件(StreamingAssets)路径
configPath = Path.Combine(Application.streamingAssetsPath,"Config.txt");
if (dic == null)
{
dic = new Dictionary<string, Dictionary<string, string>>();
LoadConfig();
}
}
/// <summary>
/// 处理所有的数据
/// </summary>
private void LoadConfig()
{
string[] lines = null;
if (File.Exists(configPath))
{
lines = File.ReadAllLines(configPath);
BuildDic(lines);
}
}
/// <summary>
/// 处理所有的数据
/// </summary>
/// <param name="lines"></param>
void BuildDic(string[] lines)
{
string mainKey = null;//主键
string subKey = null;//子键
string subValue = null;//值
foreach (var item in lines)
{
string line =