Git Product home page Git Product logo

Comments (5)

googollee avatar googollee commented on June 12, 2024

@jgoodall I can't understand it clearly. Could you show me a complete code to demo the usage?

from go-socket.io.

googollee avatar googollee commented on June 12, 2024

@jgoodall Is there any more information?

from go-socket.io.

jgoodall avatar jgoodall commented on June 12, 2024

Sorry for the delay - I think I got it working. I was testing in Firefox v 31.0 on Mac and I am not seeing any data printed in the log. It does seem to work find in Chrome v 36.0.1985.125. I am guessing the issue with Firefox has to do with the socket.io client (v 1.0.6)?

This is just a test, but really I want to listen on a channel and broadcast to all socket.io clients. I am keeping a map of clients, which was the only way I found to get it working. Does that seem right?

Thanks.

Here is the server code:

package main

import (
  "fmt"
  "log"
  "net/http"
  "time"

  "github.com/googollee/go-socket.io"
)

var sioPort uint16 = 8800
var sioRoom string = "stream"
var sioMsgType string = "event"

// list of socket.io clients
var clients = make(map[string]socketio.Socket)

// listen for messages on channel and broadcast to the room
func broadcast(c chan string, sioRoom, msgType string) {
  for {
    msg := <-c
    for _, client := range clients {
      client.BroadcastTo(sioRoom, msgType, msg)
    }
  }
}

// test
func tester(c chan string) {
  time.Sleep(time.Duration(10 * time.Second))
  log.Println("Starting test...")
  for i := 0; i < 100000; i++ {
    time.Sleep(time.Duration(10 * time.Millisecond))
    c <- fmt.Sprintf("{\"test\":%d}", i)
  }
  log.Println("Ended test.")
}

func main() {
  server := socketio.NewServer(socketio.DefaultConfig)
  server.On("connection", func(so socketio.Socket) {
    id := so.Id()
    log.Printf("Client %s connected", id)
    so.Join(sioRoom)
    clients[id] = so
    log.Print(clients[id])
    so.On("disconnection", func() {
      log.Printf("Client %s disconnect", id)
      delete(clients, id)
    })
  })
  server.On("error", func(so socketio.Socket, err error) {
    log.Printf("Socket.io Error for client %s: %s", so.Id(), err)
  })

  ch := make(chan string)
  go broadcast(ch, sioRoom, sioMsgType)
  go tester(ch)

  // startup the web server
  http.Handle("/socket.io/", server)
  http.Handle("/", http.FileServer(http.Dir("./webroot")))
  log.Printf("Listening on port %d...", sioPort)
  log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", sioPort), nil))

}

And here is the client javascript code:

<html>
  <head>
    <title>test</title>
    <script src="/socket.io-1.0.6.js"></script>
  </head>
  <body>
    <h2>socket.io test</h2>
    <div>Count: <span id="count">0</span> events</div>
    <div>Rate: <span id="rate">0</span> events per second</div>

    <script>
      // var server = "http://localhost:8800/stream";
      // var socket = io.connect(server);

      var socket = io();
      var count = 0;
      var start = false;

      socket.on("connect", function(e){
        console.info("socket.io connected");
        var seconds = 0;
        setInterval(function() {
          if (start) {
            seconds++;
            document.getElementById('rate').innerHTML = (count / seconds);            
          }
        }, 1000 );
      });
      socket.on("disconnect", function() {
        console.info("socket.io disconnected from the server");
      });
      socket.on("event", function(data) {
        if (! start) { start=true; }
        document.getElementById('count').innerHTML = count++;
        console.log(data)
      });
      socket.on("error", function(e) {
        console.info("socket.io error: " + e);
      });

    </script>
  </body>
</html>

from go-socket.io.

jgoodall avatar jgoodall commented on June 12, 2024

I am basically asking the same thing as #29. In nodejs, you can do:

var io = require('socket.io')();
io.emit('an event sent to all connected clients');

from go-socket.io.

mtsgrd avatar mtsgrd commented on June 12, 2024

Not sure how it should be solved, but here's one solution: #38

from go-socket.io.

Related Issues (20)

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.