1:python中使用websockets的建立服务器
参考文章:Python3+WebSockets实现WebSocket通信
#服务端
#coding=utf-8
import asyncio
from encodings import utf_8
from hashlib import new
import websockets
import json
# 接收客户端消息并处理
async def recv_msg(websocket):
while True:
# recv_text = await websocket.recv()
# response_text = f"your submit context: {recv_text}"
# await websocket.send(response_text)
async for message in websocket:
if isinstance(message,bytes): #如果是bytes类型,则转为str
message = message.decode() #string,encode默认编码方式是utf-8
print(type(message))
print(message)
data = json.loads(message)
print(data['health'])
print(data['cards'])
new_data = json.dumps(data,ensure_ascii=False)
await websocket.send(new_data) #接收数据后发送回去
# 服务器端主逻辑
# websocket和path是该函数被回调时自动传过来的,不需要自己传
async def main_logic(websocket, path):
await recv_msg(websocket)
# 把ip换成自己本地的ip 使用ipconfig.exe查看
start_server = websockets.serve(main_logic, '192.168.1.1', 8080)
# 如果要给被回调的main_logic传递自定义参数,可使用以下形式
# 一、修改回调形式
# import functools
# start_server = websockets.serve(functools.partial(main_logic, other_param="test_value"), '10.10.6.91', 5678)
# 修改被回调函数定义,增加相应参数
# async def main_logic(websocket, path, other_param)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
2.unity中建立客户端,并使用自带的JsonUtility包装数据
Unity自带的JsonUtility的使用:unity 通过JsonUtility实现json数据的本地保存和读取
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class WebCilent : MonoBehaviour
{
ClientWebSocket ws;
CancellationToken ct;
string rec_str;
void Start()
{
WebSocket();
}
//启动客户端
public async void WebSocket()
{
try
{
ws = new ClientWebSocket();
ct = new CancellationToken();
//添加header
//ws.Options.SetRequestHeader("X-Token", "eyJhbGciOiJIUzI1N");
Uri url = new Uri("ws://192.168.1.1:8080"); //ip使用自己电脑的,使用ipconfig.exe查看,要与服务端一致
await ws.ConnectAsync(url, ct);
while (true)
{
var result = new byte[1024];
await ws.ReceiveAsync(new ArraySegment(result), new CancellationToken());//接受数据
rec_str = Encoding.UTF8.GetString(result, 0, result.Length);
Debug.Log("rec: "+ rec_str);
if (rec_str != null)
{
//解析Json
Person np = JsonUtility.FromJson(rec_str);
Debug.Log(np.health);
Debug.Log(np.ids[0]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public async void sendMsg()
{
Person p1 = new Person();
p1.health = 8000;
p1.cards = 5;
p1.ids.Add(1);
p1.ids.Add(2);
string jsonStr = JsonUtility.ToJson(p1);
Debug.Log(jsonStr);
await ws.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(jsonStr)), WebSocketMessageType.Binary, true, ct); //发送数据
}
}
[Serializable]//序列化
public class Person
{
public int health;
public int cards;
public List ids;
public Person()
{
ids = new List();
}
}