客户端
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using UnityEngine;
public enum HeroType
{
Warrior,//战士
Master,//法师
Shooter//射手
}
//注意这个属性不能少
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Hero
{
//英雄血量
public int heroBlood;
//英雄名字
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string heroName;
//武器价格
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public int[] weaponPrice;
//武器名字
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public char[] weaponName;
//是否是男人
public bool isMan;
//英雄攻击力
public float heroAttack;
//英雄类型
public HeroType heroType;
public Hero(int heroBlood, string heroName, int[] weaponPrice, char[] weaponName, bool isMan, float heroAttack, HeroType heroType)
{
this.heroBlood = heroBlood;
this.heroName = heroName;
this.weaponPrice = weaponPrice;
this.weaponName = weaponName;
this.isMan = isMan;
this.heroAttack = heroAttack;
this.heroType = heroType;
}
}
public class TcpClient : MonoBehaviour
{
//生成socket
private Socket clientSocket;
//ip地址
private IPAddress ip;
//ip和端口号
private IPEndPoint ipEnd;
//接收的数据
private byte[] recvData = new byte[1024];
//传输的数据长度
private int recvLen;
//传输的字符串
private string recvStr;
//连接开启的线程
private Thread connectThread;
//数据总长度
private int totalSize;
//包头协议
private string hexString = string.Empty;
//包体长度
private int dataLen = 0;
//发送的数据
byte[] sendData = new byte[1024];
public Hero testStruct;
public TcpManager tcpManager;
private void Start()
{
InitSocket();
}
///
/// 初始化socket
///
private void InitSocket()
{
//获取ip和端口号
ip = IPAddress.Parse("192.168.0.11");
ipEnd = new IPEndPoint(ip, 7788);
//创建线程 在线程上运行
connectThread = new Thread(SocketReceive);
connectThread.Start();
}
///
/// byte数组转结构体
///
/// byte数组
/// 结构体类型
/// 转换后的结构体
public static object BytesToStuct(byte[] bytes, Type type)
{
//得到结构体的大小
int size = Marshal.SizeOf(type);
//byte数组长度小于结构体的大小
if (size > bytes.Length)
{
//返回空
return null;
}
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将byte数组拷到分配好的内存空间
Marshal.Copy(bytes, 0, structPtr, size);
//将内存空间转换为目标结构体
object obj = Marshal.PtrToStructure(structPtr, type);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回结构体
return obj;
}
///
/// 结构体转byte数组
///
/// 要转换的结构体
/// 转换后的byte数组
public static byte[] StructToBytes(object structObj)
{
//得到结构体的大小
int size = Marshal.SizeOf(structObj);
//创建byte数组
byte[] bytes = new byte[size];
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将结构体拷到分配好的内存空间
Marshal.StructureToPtr(structObj, structPtr, false);
//从内存空间拷到byte数组
Marshal.Copy(structPtr, bytes, 0, size);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回byte数组
return bytes;
}
///
/// 发送的数据
///
public void SendMessageToClient(string heroName, int heroBlood, int[] weaponPrice, char[] weaponName, bool isMan, float heroAttack, HeroType heroType)
{
Hero hero = new Hero(heroBlood, heroName, weaponPrice, weaponName, isMan, heroAttack, heroType);
byte[] datas = StructToBytes(hero);
clientSocket.Send(datas, datas.Length, SocketFlags.None);
}
///
/// socket 接收信息
///
private void SocketReceive()
{
SocketConnect();
//循环检测
while (true)
{
//获取数据
recvData = new byte[1024];
//获取长度
recvLen = clientSocket.Receive(recvData);
//当传输结束的时候继续挂起连接
if (recvLen == 0)
{
SocketConnect();
continue;
}
testStruct = (Hero)BytesToStuct(recvData, typeof(Hero));
GetMessage(testStruct);
//处理数据
//AnalysisData(recvData, recvLen);
}
}
private void GetMessage(Hero hero)
{
if (hero.heroName == null)
{
return;
}
tcpManager.isRecive = true;
tcpManager.reciveMessageStr = $"n一个名字叫{hero.heroName}的英雄,他现在有{hero.heroBlood}的血量,他的战斗力是{hero.heroAttack}" +
$"他有{hero.weaponName.Length}把武器,分别的是价值{hero.weaponPrice[0]}的{hero.weaponName[0].ToString() + hero.weaponName[1]}," +
$"价值{hero.weaponPrice[1]}的{hero.weaponName[2].ToString() + hero.weaponName[3]},价值{hero.weaponPrice[2]}的{hero.weaponName[4].ToString() + hero.weaponName[5]}," +
$"价值{hero.weaponPrice[3]}的{hero.weaponName[6].ToString() + hero.weaponName[7]},价值{hero.weaponPrice[4]}的{hero.weaponName[8].ToString() + hero.weaponName[9]}," +
$"价值{hero.weaponPrice[5]}的{hero.weaponName[10].ToString() + hero.weaponName[11]},他 {hero.isMan} 一个男人,同时他是{hero.heroType}";
}
///
/// 连接socket
///
private void SocketConnect()
{
//清理socket
if (clientSocket != null)
{
clientSocket.Close();
}
//创建socket
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//开始连接
clientSocket.Connect(ipEnd);
//进行判断
if (clientSocket.Connected)
{
Debug.Log("连接成功");
}
}
///
/// 解析数据(前两个字节是包头,3-7是包体长度)
///
/// 传过来的数据
/// 数据长度
private void AnalysisData(byte[] bytes, int length)
{
if (bytes != null && hexString == string.Empty)
{
//获取包头(前两个字节)(16进制)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 2; i++)
{
sb.Append(bytes[i].ToString("X2"));
}
hexString = sb.ToString();
//获取包体3-7位(int)
byte[] dataBytesLen = new byte[4];
int index = 0;
for (int i = 4; i < 8; i++)
{
dataBytesLen[index] = bytes[i];
index++;
}
dataLen = BitConverter.ToInt32(dataBytesLen, 0);
index = 0;
byte[] dataBytes = new byte[1016];
for (int i = 8; i < bytes.Length; i++)
{
dataBytes[index] = bytes[i];
index++;
}
if (dataBytes.Length > dataLen)
{
DataDispose(dataBytes, dataLen);
}
else
{
DataDispose(dataBytes, dataBytes.Length);
}
return;
}
DataDispose(bytes, length);
}
///
/// 数据处理
///
///
///
private void DataDispose(byte[] bytes, int length)
{
//计算总长度
totalSize += length;
//获取字符串
string StringMessage2 = Encoding.UTF8.GetString(bytes, 0, length);
recvStr += StringMessage2;
//当前长度与总长度相比较
if (totalSize < dataLen)
{
return;
}
//Debug.Log(recvStr);
//如果包头是FFFF协议,按照FFFF的来处理
if (hexString == "FDFD")
{
//DataManager.instance.xmlInfo = recvStr;
}
if (hexString == "FFFF")
{
///DataManager.instance.jsonInfo = recvStr;
}
hexString = string.Empty;
dataLen = 0;
recvStr = string.Empty;
totalSize = 0;
}
///
/// 发送数据
///
///
private void SocketSend(string sendStr)
{
//清空发送缓存
sendData = new byte[1024];
//数据类型转换
sendData = Encoding.ASCII.GetBytes(sendStr);
//发送
clientSocket.Send(sendData, sendData.Length, SocketFlags.None);
}
private void OnApplicationQuit()
{
//关闭线程
if (connectThread != null)
{
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭服务器
if (clientSocket != null)
clientSocket.Close();
Debug.Log("关闭连接");
}
string sendStr;
}
服务端
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
//命名空间
using System.Runtime.InteropServices;
using System;
using System.Collections.Generic;
//英雄类型
public class TcpServer : MonoBehaviour
{
//以下默认都是私有的成员
private Socket serverSocket; //服务器端socket
private Socket clientSocket; //客户端socket
private IPEndPoint ipEnd; //侦听端口
private string recvStr; //接收的字符串
private string sendStr; //发送的字符串
private byte[] recvData = new byte[1024]; //接收的数据,必须为字节
private byte[] sendData = new byte[1024]; //发送的数据,必须为字节
private int recvLen; //接收的数据长度
private Thread connectThread; //连接线程
public Hero testStruct;
public TcpManager tcpManager;
///
/// 初始化
///
private void InitSocket()
{
//定义侦听端口,侦听任何IP
ipEnd = new IPEndPoint(IPAddress.Any, 7788);
//定义套接字类型,在主线程中定义
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接
serverSocket.Bind(ipEnd);
//开始侦听,最大10个连接
serverSocket.Listen(10);
//开启一个线程连接,必须的,否则主线程卡死
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
///
/// 结构体转byte数组
///
/// 要转换的结构体
/// 转换后的byte数组
public static byte[] StructToBytes(object structObj)
{
//得到结构体的大小
int size = Marshal.SizeOf(structObj);
//创建byte数组
byte[] bytes = new byte[size];
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将结构体拷到分配好的内存空间
Marshal.StructureToPtr(structObj, structPtr, false);
//从内存空间拷到byte数组
Marshal.Copy(structPtr, bytes, 0, size);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回byte数组
return bytes;
}
///
/// byte数组转结构体
///
/// byte数组
/// 结构体类型
/// 转换后的结构体
public static object BytesToStuct(byte[] bytes, Type type)
{
//得到结构体的大小
int size = Marshal.SizeOf(type);
//byte数组长度小于结构体的大小
if (size > bytes.Length)
{
//返回空
return null;
}
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将byte数组拷到分配好的内存空间
Marshal.Copy(bytes, 0, structPtr, size);
//将内存空间转换为目标结构体
object obj = Marshal.PtrToStructure(structPtr, type);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回结构体
return obj;
}
///
/// 发送的数据
///
public void SendMessageToClient(string heroName, int heroBlood, int[] weaponPrice, char[] weaponName, bool isMan, float heroAttack, HeroType heroType)
{
Hero hero = new Hero(heroBlood, heroName, weaponPrice, weaponName, isMan, heroAttack, heroType);
byte[] datas = StructToBytes(hero);
clientSocket.Send(datas, datas.Length, SocketFlags.None);
}
//连接
void SocketConnet()
{
if (clientSocket != null)
clientSocket.Close();
//控制台输出侦听状态
print("Waiting for a client");
//一旦接受连接,创建一个客户端
clientSocket = serverSocket.Accept();
//获取客户端的IP和端口
IPEndPoint ipEndClient = (IPEndPoint)clientSocket.RemoteEndPoint;
//输出客户端的IP和端口
print("Connect with " + ipEndClient.Address.ToString() + ":" + ipEndClient.Port.ToString());
//SendMessageToClient();
//连接成功则发送数据
//sendStr = StructToBytes();
sendStr = "开始模拟!";
SocketSend(sendStr);
}
void SocketSend(string sendStr)
{
//清空发送缓存
sendData = new byte[1024];
//数据类型转换
sendData = Encoding.UTF8.GetBytes(sendStr);
//发送
clientSocket.Send(sendData, sendData.Length, SocketFlags.None);
}
//服务器接收
void SocketReceive()
{
//连接
SocketConnet();
//进入接收循环
while (true)
{
//对data清零
recvData = new byte[1024];
//获取收到的数据的长度
recvLen = clientSocket.Receive(recvData);
//如果收到的数据长度为0,则重连并进入下一个循环
if (recvLen == 0)
{
SocketConnet();
continue;
}
testStruct = (Hero)BytesToStuct(recvData, typeof(Hero));
GetMessage(testStruct);
//输出接收到的数据
//recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
//print(recvStr);
//将接收到的数据经过处理再发送出去
//sendStr = "From Server: " + recvStr;
//SocketSend(sendStr);
}
}
private void GetMessage(Hero hero)
{
if (hero.heroName == null)
{
return;
}
tcpManager.isRecive = true;
tcpManager.reciveMessageStr = $"n一个名字叫{hero.heroName}的英雄,他现在有{hero.heroBlood}的血量,他的战斗力是{hero.heroAttack}" +
$"他有{hero.weaponName.Length}把武器,分别的是价值{hero.weaponPrice[0]}的{hero.weaponName[0].ToString()+ hero.weaponName[1]}," +
$"价值{hero.weaponPrice[1]}的{hero.weaponName[2].ToString() + hero.weaponName[3]},价值{hero.weaponPrice[2]}的{hero.weaponName[4].ToString() + hero.weaponName[5]}," +
$"价值{hero.weaponPrice[3]}的{hero.weaponName[6].ToString() + hero.weaponName[7]},价值{hero.weaponPrice[4]}的{hero.weaponName[8].ToString() + hero.weaponName[9]}," +
$"价值{hero.weaponPrice[5]}的{hero.weaponName[10].ToString()+ hero.weaponName[11]},他 {hero.isMan} 一个男人,同时他是{hero.heroType}";
}
//连接关闭
void SocketQuit()
{
//先关闭客户端
if (clientSocket != null)
clientSocket.Close();
serverSocket.Close();
//再关闭线程
if (connectThread != null)
{
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭服务器
print("diconnect");
}
// Use this for initialization
void Start()
{
InitSocket(); //在这里初始化server
}
void OnApplicationQuit()
{
SocketQuit();
}
}
开始传输
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TcpManager : MonoBehaviour
{
public InputField heroName;
public InputField heroBlood;
public InputField heroAttack;
public Toggle isMan;
public Dropdown heroTypeDropdown;
public Button sendBtn;
public Button getWeapon;
public TcpClient tcpClient;
public TcpServer tcpServer;
public Transform weaponName;
public Transform weaponPrice;
private string allWeaponName;
private char[] first = new char[6] { '大', '小', '长', '短', '铁', '木' };
private char[] second = new char[6] { '剑', '刀', '棍', '棒', '枪', '锤' };
private char[] weaponAllName = new char[12];
private int[] weaponAllPrice = new int[6];
List heroTypes = new List { "战士", "法师", "射手"};
private HeroType heroType;
public string reciveMessageStr;
public bool isRecive;
public Text reciveMessage;
private void Start()
{
SetDropDown();
sendBtn.onClick.AddListener(SendMessage);
getWeapon.onClick.AddListener(GetWeapon);
}
private void Update()
{
if (isRecive)
{
reciveMessage.text = reciveMessageStr;
isRecive = false;
}
}
private void SetDropDown()
{
heroTypeDropdown.ClearOptions();
heroTypeDropdown.AddOptions(heroTypes);
heroTypeDropdown.onValueChanged.AddListener(SetOrder);
}
private void SetOrder(int arg0)
{
heroType = HeroType(arg0);
}
private HeroType HeroType(int num)
{
return (HeroType)num;
}
private void GetWeapon()
{
allWeaponName = null;
for (int i = 0; i < 6; i++)
{
weaponName.GetChild(i).GetComponent().text = GetWeaponName();
weaponAllPrice[i] = GetPrice();
weaponPrice.GetChild(i).GetComponent().text = weaponAllPrice[i].ToString();
allWeaponName += weaponName.GetChild(i).GetComponent().text;
}
GetCharName();
}
private void SendMessage()
{
if (tcpClient!=null)
{
tcpClient.SendMessageToClient(heroName.text, ((int)ChangeType(heroBlood.text)), weaponAllPrice, weaponAllName,
isMan.isOn, ChangeType(heroAttack.text), heroType);
}
else
{
tcpServer.SendMessageToClient(heroName.text, ((int)ChangeType(heroBlood.text)), weaponAllPrice, weaponAllName,
isMan.isOn, ChangeType(heroAttack.text), heroType);
}
}
private float ChangeType(string str)
{
if (float.TryParse(str, out float aa))
{
return aa;
}
else
{
return aa;
}
}
private string GetWeaponName()
{
int firstindex = UnityEngine.Random.Range(0, 5);
int secondindex = UnityEngine.Random.Range(0, 5);
string weapon = first[firstindex].ToString() + second[secondindex];
return weapon;
}
private int GetPrice()
{
int price = UnityEngine.Random.Range(0, 500);
return price;
}
private void GetCharName()
{
for (int i = 0; i < allWeaponName.Length; i++)
{
weaponAllName[i] = allWeaponName[i];
}
}
}