1、Unity端创建名为UnityClient.cs脚本代码(客户端):
注意:unity的规则中类,名和脚本文件名需要相同。
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class UnityClient : MonoBehaviour
{
TcpClient client;
NetworkStream stream;
public struct NPCInfo
{
public string Name;//名字
public int MaxHP;//血量
public int Attack;//攻击力
public float AttackFrequency;//攻速
}
public string serverIP = "127.0.0.1"; //服务器端ip地址
public int serverPort = 25001; //服务器端的端口号
public NPCInfo MyNPCInfo = new NPCInfo
{
Name = "UnityNPC",
MaxHP = 20,
Attack = 1,
AttackFrequency = 1,
};
void Start() //游戏开始时调用,仅调用一次
{
ConnectToServer();
}
void ConnectToServer()
{
client = new TcpClient(serverIP, serverPort);
stream = client.GetStream();
Debug.Log("成功连接到服务器");
}
void Update() //每帧都会调用
{
ReceiveMessage();
if (Input.GetKeyDown(KeyCode.U)) //判断是否按键按下u键
{
SendMessage(MyNPCInfo);
}
}
void SendMessage(NPCInfo npcInfo)
{
// 将NPCInfo实例转换为JSON格式
string json = JsonUtility.ToJson(npcInfo);
byte[] data = Encoding.UTF8.GetBytes(json);
stream.Write(data, 0, data.Length);
}
void ReceiveMessage()
{
if (stream.DataAvailable)
{
byte[] responseData = new byte[1024];
int bytesRead = stream.Read(responseData, 0, responseData.Length);
string response = Encoding.UTF8.GetString(responseData, 0, bytesRead);
DecodeJSON(response);
}
}
public void DecodeJSON(string json)
{
// 使用JsonUtility.FromJson<T>解码JSON数据
NPCInfo npcInfo = JsonUtility.FromJson<NPCInfo>(json);
Debug.Log("名字:"+npcInfo.Name+",血量:"+npcInfo.MaxHP+",攻击力:"+npcInfo.Attack+",攻速:"+npcInfo.AttackFrequency);
}
void OnDestroy()
{
stream.Close();
client.Close();
}
}
2、服务器端的python脚本
import socket
import json
import threading
from dataclasses import dataclass
# 定义服务器的IP地址和端口号
host, port = "127.0.0.1", 25001
# 定义NPCInfo结构体
@dataclass
class NPCInfo:
Name: str
MaxHP: int
Attack: int
AttackFrequency: float
# 处理客户端连接的函数
def handle_client(client_socket):
send_thread = threading.Thread(target=send_npc_info, args=(client_socket,))
receive_thread = threading.Thread(target=receive_npc_info, args=(client_socket,))
send_thread.start()
receive_thread.start()
# 将NPCInfo实例转为JSON格式并发送给客户端
def send_npc_info(client_socket):
npc_info = NPCInfo("机器人", 100, 10, 1.5) # 示例数据
while True:
user_input = input("输入P发送信息")
if user_input.lower() == 'p':
json_data = json.dumps(npc_info.__dict__) # 转换为JSON格式
json_data += '\n' # 添加换行符作为分隔符
client_socket.sendall(json_data.encode()) # 发送JSON数据
# 从客户端接收JSON数据并解码为NPCInfo实例
def receive_npc_info(client_socket):
while True:
received_data = client_socket.recv(1024).decode() # 接收数据并解码为字符串
if not received_data:
break
# 解码JSON数据为NPCInfo实例
npc_data = json.loads(received_data)
npc_info = NPCInfo(**npc_data)
print("收到Unity信息:", npc_info)
# 创建TCP socket并绑定IP地址和端口号
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
print(f"正在监听 {host}:{port}")
while True:
# 等待客户端连接
client_socket, _ = server_socket.accept()
print(f"成功连接到客户端 {_}")
# 启动一个线程来处理客户端连接
client_thread = threading.Thread(target=handle_client, args=(client_socket,))
client_thread.start()
3、运行,先运行服务器端python程序,再运行unity上的游戏。
服务器端成功链接Unity客户端,按下P键会发送消息到Unity客户端。
代码摘自:https://www.bilibili.com/read/cv32863690/?jump_opus=1 出处:bilibili