赞
踩
const WebSocket = require(‘ws’) const wss = new WebSocket.Server({
port: 8080 },()=>{
console.log(‘server started’) }) wss.on(‘connection’, function connection(ws) { ws.on(‘message’, (data) => {
console.log(‘data received \n %o’,data)
ws.send(data); }) })
wss.on(‘listening’,()=>{
console.log(‘listening on 8080’)
})
WebSocket 服务器模块事件
WebSocket 客户端模块事件
一旦我们捕获连接的客户端,我们就会监听客户端上的“消息”事件并收集从客户端发送的数据,然后将其发送回同一客户端。
启动服务器时,您应该在终端中看到以下内容
using UnityEngine; using WebSocketSharp; public class WsClient : MonoBehaviour { WebSocket ws; private void Start() { ws = new WebSocket("ws://localhost:8080"); ws.Connect(); ws.OnMessage += (sender, e) => { Debug.Log("Message Received from "+((WebSocket)sender).Url+", Data : "+e.Data); }; } private void Update() { if(ws == null) { return; } if (Input.GetKeyDown(KeyCode.Space)) { ws.Send("Hello"); } } }
ws = new WebSocket("ws://localhost:8080");
ws.Connect();
ws.OnMessage += (sender, e) =>
{
Debug.Log("Message Received from "+((WebSocket)sender).Url+", Data : "+e.Data);
};
private void Update()
{
if(ws == null)
{
return;
}
if (Input.GetKeyDown(KeyCode.Space))
{
ws.Send("Hello");
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。