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();
}
}
|