BestHTTP SocketIO3 简单回调示例 callback
unity c# client:
private void Start()
{
var socketManager = new SocketManager(new System.Uri(string.Format("{0}:{1}", "127.0.0.1", "6000")));
socket = socketManager.Socket;
socket.On<ConnectResponse> (SocketIOEventTypes.Connect, OnConnected); //连接
socket.On(SocketIOEventTypes.Disconnect, OnDisconnected);
socket.On<Socket,Dictionary<string, string>>("GameMessage", OnReadMessage);
socket.On<Dictionary<string, string>>("start", ConnectedMessage);
}
private void ConnectedMessage(Dictionary<string, string> msg)
{
Debug.Log("第一次 Connected! :");
foreach (var item in msg)
{
Debug.Log("接收发送回来的start "+ item);
}
//发送一个可以回调的消息 ExpectAcknowledgement
socket.ExpectAcknowledgement<Dictionary<string, string>>((dict) =>
{
foreach (var item in dict)
{
Debug.Log("回调: " + item);
}
}).Emit("message", msg);
}
// 接收消息 并且反馈给server
private void OnReadMessage(Socket socket, Dictionary<string, string> msg)
{
Dictionary<string, string> keyValues = msg;
foreach (var item in keyValues)
{
Debug.LogWarning("收到服务器消息:" + item);
}
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("clientmsg", "谢谢你Server!");
socket.EmitAck(data);
}
node Server:
let express = Express();
const httpServer: any = HTTP.createServer(express);
const IO = new Server(httpServer, { pingTimeout: 9999999, pingInterval: 999999 });
IO.on('connection', (socket: any) => {
console.log(socket.id);
socket.emit("start", {msg: 'ok!'});
socket.on("message", (data:any, callback:Function)=>{
console.log("接收消息: " , data);
if(callback) callback({back:'回调参数!'});
});
socket.emit("GameMessage", { msg: '你好!'}, (ref:any)=>{
console.log("返回客户端回调: ", ref);
});
});
httpServer.listen(6000, () => {
if (httpServer != null) {
const port = httpServer.address().port
let str = 'start socket.io server! listening on *:' + port;
console.log(str);
}
});
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。