当前位置:网站首页>Unity Socket
Unity Socket
2022-04-21 19:47:00 【ThursdayGame】
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class NetSocket : MonoBehaviour
{
public static NetSocket instance;
private void Awake()
{
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
instance = this;
DontDestroyOnLoad(this);
ConnectServer();
}
public string IP;
public int Port;
bool isReceived = false;
string message;
public Action<string> receivedToDo;
private void Update()
{
if (isReceived)
{
isReceived = false;
receivedToDo?.Invoke(message);
}
if (timecount > 0)
{
timecount -= Time.deltaTime;
}
else
{
timecount = 1f;
if (isConnected)
{
Send("HeartBeat!");
}
}
}
float timecount = 0.25f;
public bool isConnected = false;
/// <summary>
/// 连接服务器
/// </summary>
static Socket socket_client;
Thread receiveThread;
public void ConnectServer()
{
try
{
IPAddress pAddress = IPAddress.Parse(IP);
IPEndPoint pEndPoint = new IPEndPoint(pAddress, Port);
socket_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket_client.Connect(pEndPoint);
isConnected = true;
if (receiveThread == null)
{
receiveThread = new Thread(new ThreadStart(Received));
receiveThread.Start();
}
else
{
receiveThread.Abort();
receiveThread = new Thread(new ThreadStart(Received));
receiveThread.Start();
}
}
catch (System.Exception)
{
Debug.Log("IP端口号错误或者服务器未开启");
}
}
/// <summary>
/// 读取服务器消息
/// </summary>
public void Received()
{
while (true)
{
try
{
byte[] buffer = new byte[1024];
int len = socket_client.Receive(buffer);
//Debug.Log(len);
if (len == 0) break;
string stt = Encoding.UTF8.GetString(buffer, 0, 4);
//Debug.Log(stt);
//Debug.Log(int.Parse(stt));
stt = Encoding.UTF8.GetString(buffer, 4, int.Parse(stt));
Debug.Log("客户端打印服务器返回消息:" + socket_client.RemoteEndPoint + " : " + stt + " " + stt.Length);
message = stt;
isReceived = true;
}
catch (System.Exception e)
{
Debug.Log(e.Message);
if (isConnected == false)
{
break;
}
}
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="msg"></param>
public void Send(string msg)
{
try
{
int n = 0, i = 0;
int length = n = msg.Length;
for (i = 0; n > 0; i++)
{
n /= 10;
}
string head = "";
for (int j = 0; j < i; j++)
{
head += "0";
}
head += length;
byte[] buffer = new byte[1024];
string message = head + msg;
// Debug.Log("[" + DateTime.Now + "]" + message);
buffer = Encoding.UTF8.GetBytes(message);
socket_client.Send(buffer);
}
catch (System.Exception)
{
Debug.Log("未连接");
isConnected = false;
ConnectServer();
}
}
/// <summary>
/// 关闭连接
/// </summary>
public void close()
{
try
{
socket_client.Close();
Debug.Log("关闭客户端连接");
isConnected = false;
// SceneManager.LoadScene("control");
}
catch (System.Exception)
{
isConnected = false;
Debug.Log("未连接");
}
}
void OnDisable()
{
if (isConnected)
{
close();
}
}
}
public class ByteBuffer
{
MemoryStream stream = null;
BinaryWriter writer = null;
BinaryReader reader = null;
public ByteBuffer()
{
stream = new MemoryStream();
writer = new BinaryWriter(stream);
}
public ByteBuffer(byte[] data)
{
if (data != null)
{
stream = new MemoryStream(data);
reader = new BinaryReader(stream);
}
else
{
stream = new MemoryStream();
writer = new BinaryWriter(stream);
}
}
public void Close()
{
if (writer != null) writer.Close();
if (reader != null) reader.Close();
stream.Close();
writer = null;
reader = null;
stream = null;
}
public void WriteByte(byte v)
{
writer.Write(v);
}
public void WriteInt(int v)
{
writer.Write((int) v);
}
public void WriteShort(ushort v)
{
writer.Write((ushort) v);
}
public void WriteLong(long v)
{
writer.Write((long) v);
}
public void WriteFloat(float v)
{
byte[] temp = BitConverter.GetBytes(v);
Array.Reverse(temp);
writer.Write(BitConverter.ToSingle(temp, 0));
}
public void WriteDouble(double v)
{
byte[] temp = BitConverter.GetBytes(v);
Array.Reverse(temp);
writer.Write(BitConverter.ToDouble(temp, 0));
}
public void WriteString(string v)
{
byte[] bytes = Encoding.UTF8.GetBytes(v);
writer.Write((ushort) bytes.Length);
writer.Write(bytes);
}
public void WriteBytes(byte[] v)
{
writer.Write((int) v.Length);
writer.Write(v);
}
public byte ReadByte()
{
return reader.ReadByte();
}
public int ReadInt()
{
return (int) reader.ReadInt32();
}
public ushort ReadShort()
{
return (ushort) reader.ReadInt16();
}
public long ReadLong()
{
return (long) reader.ReadInt64();
}
public float ReadFloat()
{
byte[] temp = BitConverter.GetBytes(reader.ReadSingle());
Array.Reverse(temp);
return BitConverter.ToSingle(temp, 0);
}
public double ReadDouble()
{
byte[] temp = BitConverter.GetBytes(reader.ReadDouble());
Array.Reverse(temp);
return BitConverter.ToDouble(temp, 0);
}
public string ReadString()
{
ushort len = ReadShort();
byte[] buffer = new byte[len];
buffer = reader.ReadBytes(len);
return Encoding.UTF8.GetString(buffer);
}
public byte[] ReadBytes()
{
int len = ReadInt();
return reader.ReadBytes(len);
}
public byte[] ToBytes()
{
writer.Flush();
return stream.ToArray();
}
public void Flush()
{
writer.Flush();
}
}
版权声明
本文为[ThursdayGame]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_42680589/article/details/124282177
边栏推荐
- 杰理之低功耗休眠【篇】
- MKL library matrix multiplication
- 学完这篇Charles抓包教程,我直接把fiddler卸载了
- 【JZ47 礼物的最大价值】
- fiddler抓包PC微信小程序失败的解决方案
- MYSQL输入密码后闪退的解决方法
- 危化品企业双预防机制数字化建设综合解决方案
- 【2021】腾讯秋招技术岗编程 有效序列的数量
- Frame rate, code rate, resolution and definition
- B / s interface control devextreme ASP Net MVC Getting Started Guide - template syntax (I)
猜你喜欢

高端制造業企業信息化解决方案,工業電商平臺設備、數據、體系預測性維護

Enterprise cross-border e-commerce platform service solution, cross-border e-commerce trade business framework construction, operation and maintenance

getchar,putchar,EOF

Flitter Xcode packaging and publishing failed error ninety thousand one hundred and sixty-five

Mysql错误2005

leetcode541. Reverse string II

iMeta | EndNote调整完美引文格式教程(视频)

2023年南开大学税务专硕考研上岸前辈备考经验指导

DolphinDB VSCode 插件使用教程

SAP PS 第12节 网络成本计划
随机推荐
有趣的灵魂千篇一律,电脑滑动关机,仅需2步
Building / Qt 5 and QT 6 compatibility using cmake
redis安装与配置开机自启
学完这篇Charles抓包教程,我直接把fiddler卸载了
杰理之使用不可屏蔽中断的开关中断函数【篇】
剑指Offer:[第29天 动态规划(困难)]--->n个骰子的点数
多因子策略
leetcode541. 反转字符串 II
杰理之使用硬件定时器来模拟中断请求【篇】
PostgreSql 连接访问控制
调试 ms 源代码
[netty] is it difficult to implement a redis client by yourself?
居家第二十一天的成果
状态码封装--转载
flink中checkpoint机制随笔
Chekine series high density lipoprotein (HDL-C) content detection scheme
照片删除了怎么恢复?4个方案,这才是官方指南
06.适配器模式
杰理之不可屏蔽中断【篇】
企业跨境电商平台服务解决方案,跨境电子商务贸易业务框架搭建运维