翻翻过去那场雪
如果您已经使用 Javascript 一段时间了,那么实现您自己的 Javascript 版本真的很容易socket.on,socket.emit这里是我为自己的项目制作的版本,但如果您需要,您可以拥有它,// e.g.// let socket = new Socket("ws://w/e");// socket.on('connected', () => { console.log('Connected'); });// socket.emit('lobby join', { data: { username: 'Boo' } });// Using ES2015 with Babelimport {EventEmitter} from 'events';class Socket { constructor(wsurl, ee = new EventEmitter()) { let ws = new WebSocket(wsurl); this.ee = ee; this.ws = ws; ws.onmessage = this.message.bind(this); ws.onopen = this.open.bind(this); ws.onclose = this.close.bind(this); } on(name, fn) { this.ee.on(name, fn); } off(name, fn) { this.ee.removeListener(name, fn); } emit(name, data) { const message = JSON.stringify({name, data}); this.ws.send(message); } message(e) { try { const msgData = JSON.parse(e.data); this.ee.emit(msgData.name, msgData.data); } catch(err) { let error = { message: err } console.log(err) this.ee.emit(error.message) } } open() { this.ee.emit('connected'); } close() { this.ee.emit('disconnected'); } }export default Socket这将让你使用你的共同socket.on('event', fn);和什么不至于在服务器端处理:对于接收消息,我个人只是创建一个 switch 语句,将传入的字符串与函数匹配,例如:// readPump pumps messages from the websocket connection to the hub.func (c *connection) readPump() { defer c.ws.Close() for { _, message, err := c.ws.ReadMessage() if err != nil { break } var incMessage interface{} err = json.Unmarshal(message, &incMessage) if err != nil { log.Println(err) } incMessageMap := incMessage.(map[string]interface{}) switch incMessageMap["name"] { case "lobby join": // Do something to handle joining case "lobby leave": // Do something to handle leaving } }}为了发送它们send channel,我的连接上有一个存储在地图中的连接,当我需要发出时,我有一个简单的结构,它采用消息名称和数据,例如:type wsMsg struct { Name string `json:"name"` Data map[string]interface{} `json:"data"`}c.send <- wsMsg{ "user joined", map[string]interface{}{ "username": "Booh", },}然后在客户端它会变成socket.on('user joined', (msg) => { console.log(msg) // { username: "Booh" }});我建议查看 gorillas git 上的示例:https : //github.com/gorilla/websocket/tree/master/examples/chat