baiguoshuai1 / shadiaosocketio Goto Github PK
View Code? Open in Web Editor NEWA simple Go SocketIO and support for protocol 3 and protocol 4!
A simple Go SocketIO and support for protocol 3 and protocol 4!
How could I define server with namespaces?
In client I could do io("/chat", {transports: ["websocket"]})
I have a program through socket.io 4.5 as a communication protocol, is the use of node.js development, I want to use golang as a client language, but encountered the do not know how to be able to send the callback to the server side of the problem, want to know the current have to do this function?
I can't run the "c.broadcast" command. I can even do it, but he doesn't send it
Due to how ACK ID is parsed
// handler.go:187
ackId, _ := strconv.Atoi(string(msg[1]))
Because it reads only second character of received message, it will fail for IDs larger than 10, which getNextId
is generating. Therefore, waiters with ID >= 10 always timeout.
It does not comply with the socket.io protocol:
message:
{ type: ACK, data: ["bar"], id: 13 }
encoded:
313["bar"]
ID of that message is 13
, shadiaosocketio will read it as 1
.
l will work on PR.
Golang server:
package main
import (
"github.com/Baiguoshuai1/shadiaosocketio"
"github.com/Baiguoshuai1/shadiaosocketio/websocket"
"log"
"net/http"
"time"
)
type Message struct {
Id int `json:"id"`
Channel string `json:"channel"`
}
type Desc struct {
Text string `json:"text"`
}
func main() {
server := shadiaosocketio.NewServer(*websocket.GetDefaultWebsocketTransport())
server.On(shadiaosocketio.OnConnection, func(c *shadiaosocketio.Channel) {
log.Println("[server] connected! id:", c.Id())
log.Println("[server]", c.RemoteAddr().Network()+" "+c.RemoteAddr().String()+
" --> "+c.LocalAddr().Network()+" "+c.LocalAddr().String())
c.Join("room")
server.BroadcastTo("room", "/admin", Message{1, "new members!"})
time.Sleep(100 * time.Millisecond)
c.BroadcastTo("room", "/admin", Message{2, "hello everyone!"})
_ = c.Emit("message", Message{10, "{\"chinese\":\"中文才是最屌的\"}"})
// return [][]byte
result, err := c.Ack("/ackFromServer", time.Second*5, "go", 3)
if err != nil {
log.Println("[server] ack cb err:", err)
return
}
log.Println("[server] ack cb:", result)
time.Sleep(3 * time.Second)
log.Println("ReadBytes", c.ReadBytes())
log.Println("WriteBytes", c.WriteBytes())
})
server.On(shadiaosocketio.OnDisconnection, func(c *shadiaosocketio.Channel, reason websocket.CloseError) {
log.Println("[server] received disconnect", c.Id(), "code:", reason.Code, "text:", reason.Text)
})
server.On("message", func(c *shadiaosocketio.Channel, arg1 string, arg2 Message, arg3 int, arg4 bool) {
log.Println("[server] received message:", "arg1:", arg1, "arg2:", arg2, "arg3:", arg3, "arg4:", arg4)
})
// listen ack event
server.On("/ackFromClient", func(c *shadiaosocketio.Channel, msg Message, num int) (int, Desc, string) {
log.Println("[server] received ack:", msg, num)
return 1, Desc{Text: "resp"}, "server"
})
serveMux := http.NewServeMux()
serveMux.Handle("/socket.io/", server)
serveMux.Handle("/", http.FileServer(http.Dir("assets")))
log.Println("[server] starting server...")
log.Panic(http.ListenAndServe(":2233", serveMux))
}
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://unpkg.com/[email protected]/dist/socket.io.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io("ws://127.0.0.1:2233",{transports: ['websocket']})
// listen for messages
socket.on('message', function(msg) {
console.log('[client] received msg:', msg);
});
// sending ack response
socket.on('/ackFromServer', function(a, b, f) {
console.log('[client] received ack:', a , b);
f({ id: 5, channel: 'js channel' }, 6)
});
socket.on('/admin', function(msg) {
console.log('[client] received admin msg:', msg);
});
socket.on('connect', function () {
console.log('[client] socket connected');
socket.emit('message', "js", { id: 1, channel: "js" }, 2);
// ack
socket.emit('/ackFromClient', { id: 3, channel: "js ack" }, 4, (a, b, c) => {
console.log('[client] ack cb:', a, b, c)
});
});
socket.on('disconnect', function (e) {
console.log('[client] socket disconnect', e);
});
socket.on('connect_error', function (e) {
console.log('[client] connect_error', e)
});
</script>
</body>
</html>
Error Received:
On server
2023/08/27 22:36:09 http: superfluous response.WriteHeader call from github.com/Baiguoshuai1/shadiaosocketio/websocket.(*Transport).HandleConnection (websocket.go:305)
On browser
WebSocket connection to 'ws://127.0.0.1:2233/socket.io/?EIO=4&transport=websocket' failed:
value @ websocket.js:44
value @ transport.js:45
value @ socket.js:164
a @ socket.js:105
value @ manager.js:108
(anonymous) @ manager.js:331
(index):57 [client] connect_error Error: websocket error
at i.value (transport.js:37:37)
at ws.onerror (websocket.js:70:39)
This empties channel https://github.com/Baiguoshuai1/shadiaosocketio/blob/main/channel.go#L138
And bloks this goroutime forever https://github.com/Baiguoshuai1/shadiaosocketio/blob/main/channel.go#L216.
instead we should send protocol.CloseMsg so that for loop exits and go routine cleans itself
Transport
contains UnsecureTLS
to configure tls.Config
but this is unnecessary limitation to tls configuration. It would be better to allow passing tls.config
to Transport
to enable ex. self-signed certs configuration.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.