在golang中使用socket.io
Posted aguncn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在golang中使用socket.io相关的知识,希望对你有一定的参考价值。
客户端试过了socket.js,感觉不先进。
再试试正宗的socket.io吧。
后端用golang改造。
main.go
package main import ( "fmt" "log" "net/http" socketio "github.com/googollee/go-socket.io" ) func main() { server, err := socketio.NewServer(nil) if err != nil { log.Fatal(err) } //===========/chat1=========== server.OnEvent("/", "default notice", func(s socketio.Conn, msg string) { fmt.Println("default notice:", msg) s.Emit("default reply", "default notice reply: "+msg) }) //===========/chat1=========== server.OnEvent("/chat1", "chat1 notice", func(s socketio.Conn, msg string) { fmt.Println("chat1 notice:", msg) s.Emit("chat1 reply", "chat1 notice reply: "+msg) }) //===========/chat2=========== server.OnEvent("/chat2", "chat2 msg", func(s socketio.Conn, msg string) string { s.SetContext(msg) return "chat2 msg recv " + msg }) go server.Serve() defer server.Close() http.Handle("/socket.io/", server) http.Handle("/", http.FileServer(http.Dir("./asset"))) log.Println("Serving at localhost:8000...") log.Fatal(http.ListenAndServe(":8000", nil)) }
index.html
<!doctype html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket1 = io("/chat1"); var socket2 = io("/chat2"); socket1.on(‘chat1 reply‘, function(msg){ $(‘#messages‘).append($(‘<li>‘).text(msg)); }); $(‘form‘).submit(function(){ socket2.emit(‘chat2 msg‘, $(‘#m‘).val(), function(data){ console.log(data); $(‘#messages‘).append($(‘<li>‘).text(‘ACK CALLBACK: ‘ + data)); }); socket1.emit(‘chat1 notice‘, $(‘#m‘).val()); $(‘#m‘).val(‘‘); return false; }); </script> </body> </html>
以上是关于在golang中使用socket.io的主要内容,如果未能解决你的问题,请参考以下文章