Git Product home page Git Product logo

shadiaosocketio's Issues

ACK fails when ID >= 10

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.

[QUESTION] - Cannot connect to JS with HTML to server on golang

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)

`Transport` expose setting `tls.Config`

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.