发送端和服务端一体
using UnityEngine;
using System.Collections.Generic;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.SceneManagement;
public class UDPClient : MonoBehaviour
{
public static UDPClient instance;
//服务端的IP
string UDPServerIP,UDPClientIPOne,UDPClientIPTwo,UDPLocalSeverIPOne;
//目标socket
Socket socket;
//服务端
EndPoint serverEnd;
//服务端端口
IPEndPoint ipEnd;
//接收的字符串
string recvStr;
//发送的字符串
string sendStr;
//接收的数据,必须为字节
byte[] recvData = new byte[1024];
//发送的数据,必须为字节
byte[] sendData = new byte[1024];
//接收的数据长度
int recvLen = 0;
List<string> MsgPool;
//连接线程
Thread connectThread;
bool isClientActive = false;
int port;
int localPort, UserPortOne, UserPortTwo ,LocalSeverPortOne;
public delegate void UDPClientDele(string ss);
public event UDPClientDele UDPClientEvent;
private void Awake()
{
instance = this;
}
void Start()
{
UDPServerIP = Configs.instance.LoadText("LocalServerIP", "ip");//服务端的IP.自己更改
print(UDPServerIP);
localPort = int.Parse(Configs.instance.LoadText("LocalPort", "port"));
UDPLocalSeverIPOne = Configs.instance.LoadText("LocalServerIPTwo", "ip");
LocalSeverPortOne = int.Parse(Configs.instance.LoadText("LocalPortTwo", "port"));
UDPClientIPOne = Configs.instance.LoadText("UserClientIPOne", "ip");
UserPortOne = int.Parse(Configs.instance.LoadText("UserPortOne", "port"));
UDPClientIPTwo = Configs.instance.LoadText("UserClientIPTwo", "ip");
UserPortTwo = int.Parse(Configs.instance.LoadText("UserPortTwo", "port"));
UDPServerIP = UDPServerIP.Trim();
isClientActive = true;
InitSocket(); //在这里初始化
}
private void Update()
{
//if (Input.GetMouseButtonDown(0))
//{
// SocketSend("12");
//}
}
//初始化
void InitSocket()
{
//定义连接的服务器ip和端口,可以是本机ip,局域网,互联网
ipEnd = new IPEndPoint(IPAddress.Parse(UDPServerIP), localPort);
//定义套接字类型,在主线程中定义
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//定义服务端
IPEndPoint sender = new IPEndPoint(IPAddress.Parse(UDPLocalSeverIPOne), LocalSeverPortOne);
serverEnd = (EndPoint)sender;
socket.Bind(serverEnd);
//建立初始连接,这句非常重要,第一次连接初始化了serverEnd后面才能收到消息
//SocketSend("hello");
//开始心跳监听
//客户端发送心跳消息后,计时器开始计时,判断3秒内是否能收到服务端的反馈
//开启一个线程连接,必须的,否则主线程卡死
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
//发送字符串
public void SocketSend(string sendStr)
{
//清空发送缓存
sendData = new byte[1024];
//数据类型转换
sendData = Encoding.UTF8.GetBytes(sendStr);
//发送给指定服务端
// 对方端口 两个端口
socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne),UserPortOne));
socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPTwo),UserPortTwo));
//print(3333);
}
//接收服务器消息
void SocketReceive()
{
//进入接收循环
while (isClientActive)
{
//对data清零
recvData = new byte[1024];
try
{
//获取服务端端数据
recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
if (isClientActive == false)
{
break;
}
}
catch (Exception e)
{
print(e.Message);
}
//打印服务端信息
//输出接收到的数据
if (recvLen > 0)
{
//接收到的信息
recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
print(recvStr);
if (UDPClientEvent!=null)
{
UDPClientEvent(recvStr);
//print(recvStr);
}
}
}
}
//连接关闭
public void SocketQuit()
{
//关闭线程
if(connectThread != null)
{
isClientActive = false;
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭socket
if (socket != null)
socket.Close();
}
void OnApplicationQuit()
{
SocketQuit();
}
void OnDisable()
{
isClientActive = false;
SocketQuit();
Thread.Sleep(25);
}
}
UDPClient
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.SceneManagement;
public class UDPClient : MonoBehaviour
{
public static UDPClient instance;
//服务端的IP
string UDPServerIP,UDPClientIPOne,UDPClientIPTwo;
//目标socket
Socket socket;
//服务端
EndPoint serverEnd;
//服务端端口
IPEndPoint ipEnd;
//接收的字符串
string recvStr;
//发送的字符串
string sendStr;
//接收的数据,必须为字节
byte[] recvData = new byte[1024];
//发送的数据,必须为字节
byte[] sendData = new byte[1024];
//接收的数据长度
int recvLen = 0;
List<string> MsgPool;
//连接线程
Thread connectThread;
bool isClientActive = false;
int localPort, UserPortOne, UserPortTwo ;
public delegate void UDPClientDele(string ss);
public event UDPClientDele UDPClientEvent;
private void Awake()
{
instance = this;
}
void Start()
{
UDPServerIP = Configs.instance.LoadText("LocalServerIP", "ip");//服务端的IP.自己更改
print(UDPServerIP);
localPort = int.Parse(Configs.instance.LoadText("LocalPort", "port"));
//UDPLocalSeverIPOne = Configs.instance.LoadText("LocalServerIPTwo", "ip");
//LocalSeverPortOne = int.Parse(Configs.instance.LoadText("LocalPortTwo", "port"));
UDPClientIPOne = Configs.instance.LoadText("UserClientIPOne", "ip");
UserPortOne = int.Parse(Configs.instance.LoadText("UserPortOne", "port"));
UDPClientIPTwo = Configs.instance.LoadText("UserClientIPTwo", "ip");
UserPortTwo = int.Parse(Configs.instance.LoadText("UserPortTwo", "port"));
UDPServerIP = UDPServerIP.Trim();
isClientActive = true;
InitSocket(); //在这里初始化
}
private void Update()
{
//if (Input.GetMouseButtonDown(0))
//{
// SocketSend("12");
//}
}
//初始化
void InitSocket()
{
//定义连接的服务器ip和端口,可以是本机ip,局域网,互联网
//ipEnd = new IPEndPoint(IPAddress.Parse(UDPServerIP), localPort);
//serverEnd = (EndPoint)ipEnd;
//socket.Bind(serverEnd);
//定义套接字类型,在主线程中定义
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//定义服务端
IPEndPoint sender = new IPEndPoint(IPAddress.Parse(UDPServerIP), localPort);
serverEnd = (EndPoint)sender;
socket.Bind(serverEnd);
//建立初始连接,这句非常重要,第一次连接初始化了serverEnd后面才能收到消息
// SocketSend("hello");
//开始心跳监听
//客户端发送心跳消息后,计时器开始计时,判断3秒内是否能收到服务端的反馈
//开启一个线程连接,必须的,否则主线程卡死
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
//发送字符串
public void SocketSend(string sendStr)
{
//清空发送缓存
sendData = new byte[1024];
//数据类型转换
sendData = Encoding.UTF8.GetBytes(sendStr);
print(sendStr);
//发送给指定服务端
// 对方端口 两个端口
socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne),UserPortOne));
socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPTwo),UserPortTwo));
//print(3333);
}
//接收服务器消息
void SocketReceive()
{
//进入接收循环
while (isClientActive)
{
//对data清零
recvData = new byte[1024];
try
{
//获取服务端端数据
recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
if (isClientActive == false)
{
break;
}
}
catch (Exception e)
{
print(e.Message);
}
//打印服务端信息
//输出接收到的数据
if (recvLen > 0)
{
//接收到的信息
recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
print(recvStr);
if (UDPClientEvent!=null)
{
UDPClientEvent(recvStr);
print(recvStr);
}
}
}
}
//连接关闭
public void SocketQuit()
{
//关闭线程
if(connectThread != null)
{
isClientActive = false;
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭socket
if (socket != null)
socket.Close();
}
void OnApplicationQuit()
{
SocketQuit();
}
void OnDisable()
{
isClientActive = false;
SocketQuit();
Thread.Sleep(25);
}
}
UDPSever
using UnityEngine;
using System.Collections.Generic;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.SceneManagement;
public class UDPClient : MonoBehaviour
{
public static UDPClient instance;
//服务端的IP
string /*UDPClientIPOne, UDPClientIPTwo,*/UDPLocalSeverIPOne;
//目标socket
Socket socket;
//服务端
EndPoint serverEnd;
//服务端端口
IPEndPoint ipEnd;
//接收的字符串
string recvStr;
//发送的字符串
string sendStr;
//接收的数据,必须为字节
byte[] recvData = new byte[1024];
//发送的数据,必须为字节
byte[] sendData = new byte[1024];
//接收的数据长度
int recvLen = 0;
List<string> MsgPool;
//连接线程
Thread connectThread;
bool isClientActive = false;
//int port;
int /*UserPortOne ,*/LocalSeverPortOne/*, UserPortTwo*/;
public delegate void UDPClientDele(string ss);
public event UDPClientDele UDPClientEvent;
private void Awake()
{
instance = this;
}
void Start()
{
//UDPServerIP = Configs.instance.LoadText("LocalServerIP", "ip");//服务端的IP.自己更改
//localPort = int.Parse(Configs.instance.LoadText("LocalPort", "port"));
UDPLocalSeverIPOne = Configs.instance.LoadText("LocalServerIP", "ip"); ; //服务端的IP
LocalSeverPortOne = int.Parse(Configs.instance.LoadText("LocalPort", "port")); //服务端的端口
//UDPClientIPOne = Configs.instance.LoadText("UserClientIPOne", "ip");
//UserPortOne = int.Parse(Configs.instance.LoadText("UserPortOne", "port"));
//UDPClientIPTwo = Configs.instance.LoadText("UserClientIPTwo", "ip");
//UserPortTwo = int.Parse(Configs.instance.LoadText("UserPortTwo", "port"));
UDPLocalSeverIPOne = UDPLocalSeverIPOne.Trim();
isClientActive = true;
InitSocket(); //在这里初始化
}
private void Update()
{
//if (Input.GetMouseButtonDown(0))
//{
// SocketSend("12");
//}
}
//初始化
void InitSocket()
{
//定义连接的服务器ip和端口,可以是本机ip,局域网,互联网
//ipEnd = new IPEndPoint(IPAddress.Parse(UDPServerIP), localPort);
//定义套接字类型,在主线程中定义
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//定义服务端
IPEndPoint sender = new IPEndPoint(IPAddress.Parse(UDPLocalSeverIPOne), LocalSeverPortOne);
serverEnd = (EndPoint)sender;
socket.Bind(serverEnd);
//建立初始连接,这句非常重要,第一次连接初始化了serverEnd后面才能收到消息
//SocketSend("hello");
//开始心跳监听
//客户端发送心跳消息后,计时器开始计时,判断3秒内是否能收到服务端的反馈
//开启一个线程连接,必须的,否则主线程卡死
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
//发送字符串
public void SocketSend(string sendStr)
{
//清空发送缓存
sendData = new byte[1024];
//数据类型转换
sendData = Encoding.UTF8.GetBytes(sendStr);
//发送给指定服务端
// 对方端口
//socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPOne),UserPortOne));
//socket.SendTo(sendData, sendData.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(UDPClientIPTwo), UserPortTwo));
//print(3333);
}
//接收服务器消息
void SocketReceive()
{
//进入接收循环
while (isClientActive)
{
//对data清零
recvData = new byte[1024];
try
{
//获取服务端端数据
recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
if (isClientActive == false)
{
break;
}
}
catch (Exception e)
{
print(e.Message);
}
//打印服务端信息
//输出接收到的数据
if (recvLen > 0)
{
//接收到的信息
recvStr = Encoding.UTF8.GetString(recvData, 0, recvLen);
print(recvStr);
if (UDPClientEvent!=null)
{
UDPClientEvent(recvStr);
//print(recvStr);
}
}
}
}
//连接关闭
public void SocketQuit()
{
//关闭线程
if(connectThread != null)
{
isClientActive = false;
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭socket
if (socket != null)
socket.Close();
}
void OnApplicationQuit()
{
SocketQuit();
}
void OnDisable()
{
isClientActive = false;
SocketQuit();
Thread.Sleep(25);
}
}
Configs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using System.Text;
/// <summary>
/// 配置文件
/// </summary>
public class Configs : MonoBehaviour {
public static Configs instance;
private void Awake()
{
instance = this;
init();
}
private string[] keys;
public JsonData jsonData;
//初始化json
void init()
{
string filepath;
#if UNITY_EDITOR
filepath =Application.dataPath + "/StreamingAssets" + "/Config.txt";
#elif UNITY_STANDALONE_WIN
filepath =Application.dataPath + "/StreamingAssets" + "/Config.txt";
#elif UNITY_IPHONE
filepath = Application.dataPath + "/Raw" + "/Config.txt";
#elif UNITY_ANDROID
filepath = "jar:Application.dataPath + "!/assets" + "/Config.txt";
#endif
bool isContains = FileHandle.instance.isExistFile(filepath);
//Debug.Log(isContains);
if (isContains)
{
string str = FileHandle.instance.FileToString(filepath, Encoding.UTF8);
Debug.Log(str);
jsonData = JsonMapper.ToObject(str);
#region key 遍历
//IDictionary dict = jsonData as IDictionary;
//int count = 0;
//keys = new string[dict.Count];
//foreach (string key in dict.Keys)
//{
// keys[count] = key;
// Debug.Log(keys[count]);
// count++;
//}
#endregion
}
}
/// <summary>
/// 外部调用获取文字信息
/// </summary>
/// <param name="name"></param>
/// <param name="info"></param>
/// <returns></returns>
public string LoadText(string name,string info)
{
//Debug.Log("name = " + name + " info = " + info);
string str = (string)jsonData[name][info];
//Debug.Log(str);
return str;
}
/// <summary>
/// 获取子节点个数
/// </summary>
/// <returns></returns>
public int GetJsonCount()
{
return jsonData.Count;
}
/// <summary>
/// 获取子节点下子节点个数
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public int GetJsonCount(string name)
{
return jsonData[name].Count;
}
}
FileHandle
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Text;
/// <summary>
/// 读取文件
/// </summary>
public class FileHandle {
private FileHandle(){}
public static readonly FileHandle instance = new FileHandle();
//the filepath if there is a file
public bool isExistFile(string filepath){
return File.Exists(filepath);
}
public bool IsExistDirectory(string directorypath){
return Directory.Exists(directorypath);
}
public bool Contains(string Path,string seachpattern){
try{
string[] fileNames = GetFilenNames(Path,seachpattern,false);
return fileNames.Length!=0;
}
catch{
return false;
}
}
//return a file all rows
public static int GetLineCount(string filepath){
string[] rows = File.ReadAllLines(filepath);
return rows.Length;
}
/// <summary>
/// 创建文件
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
public bool CreateFile(string filepath){
try{
if(!isExistFile(filepath)){
StreamWriter sw;
FileInfo file = new FileInfo(filepath);
//FileStream fs = file.Create();
//fs.Close();
sw = file.CreateText();
sw.Close();
}
}
catch{
return false;
}
return true;
}
public string[] GetFilenNames(string directorypath,string searchpattern,bool isSearchChild){
if(!IsExistDirectory(directorypath)){
throw new FileNotFoundException();
}
try{
return Directory.GetFiles(directorypath,searchpattern,isSearchChild?SearchOption.AllDirectories:SearchOption.TopDirectoryOnly);
}
catch{
return null;
}
}
/// <summary>
/// 写入文件
/// </summary>
/// <param name="filepath">地址</param>
/// <param name="content">内容</param>
public void WriteText(string filepath,string content)
{
//File.WriteAllText(filepath,content);
FileStream fs = new FileStream(filepath,FileMode.Append);
StreamWriter sw = new StreamWriter(fs,Encoding.UTF8);
sw.WriteLine(content);
sw.Close();
fs.Close();
Debug.Log("write: filepath: "+filepath);
Debug.Log("write: content: "+content);
Debug.Log("写入完毕");
}
public void AppendText(string filepath,string content){
File.AppendAllText(filepath,content);
}
/// <summary>
/// 读取问字内容
/// </summary>
/// <param name="filepath"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public string FileToString(string filepath,Encoding encoding){
FileStream fs = new FileStream(filepath,FileMode.Open,FileAccess.Read);
StreamReader reader = new StreamReader(fs,encoding);
try{
return reader.ReadToEnd();
}
catch{
return string.Empty;
}
finally{
fs.Close();
reader.Close();
//Debug.Log("读取完毕");
}
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="filepath"></param>
public void ClearFile(string filepath){
File.Delete(filepath);
CreateFile(filepath);
}
}
网友评论