Friday, 13 November 2020

golang 16 socket.io

client 1 ping server first, then broadcast
client 1 received broadcast from client 2


//cmd - server
 
C:\Users\bob\golang6>go run main.go
2020/11/14 15:02:03 Serving at localhost:8000...
connected: 1
connected: 2
notice: client 1 ping server
notice: client 2 ping server
broadcast: hello from client 1
broadcast: hi from client 2
1 closed client namespace disconnect
2 closed client namespace disconnect
//main.go
package main

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

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

func main() {
server := socketio.NewServer(nil)

server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
s.Join("room1")
fmt.Println("connected:", s.ID())
return nil
})

server.OnEvent("/", "ping", func(s socketio.Conn, msg string) {
fmt.Println("notice:", msg)
s.Emit("pingReply", "ping: "+msg)
})

//broadcast
server.OnEvent("/", "broadcast", func(s socketio.Conn, msg string) {
fmt.Println("broadcast:", msg)
server.BroadcastToRoom("/", "room1", "serverBroadcast", "broadcast: "+msg)
})

server.OnEvent("/", "bye", func(s socketio.Conn) string {
last := s.Context().(string)
s.Emit("bye", last)
s.Close()
return last
})

server.OnError("/", func(s socketio.Conn, e error) {
fmt.Println("meet error:", e)
})

server.OnDisconnect("/", func(s socketio.Conn, reason string) {
fmt.Println(s.ID(), "closed", reason)
})

go server.Serve()
defer server.Close()

http.Handle("/socket.io/", server)
http.Handle("/", http.FileServer(http.Dir("./static")))
log.Println("Serving at localhost:8000...")
log.Fatal(http.ListenAndServe(":8000", nil))
}

----------------------
//index.html
<!doctype html>
<html>

<head>
    <title>Socket.IO chat</title>
    <link rel="stylesheet" type="text/css" href="/static/index.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font: 30px Helvetica, Arial;
        }

        #form1 {
            background: #000;
            padding: 3px;
            position: fixed;
            bottom: 0;
            width: 100%;
        }

        #form2 {
            background: #000;
            padding: 3px;
            position: fixed;
            bottom: 60px;
            width: 100%;
        }

        form input {
            border: 0;
            padding: 10px;
            width: 79%;
            margin-right: .5%;
            font-size: 30px;
        }

        form button {
            width: 20%;
            background: rgb(130, 224, 255);
            border: none;
            padding: 10px;
            font-size: 30px;
        }

        #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 id="form1" action="">
        <input id="m" autocomplete="off" /><button>Ping Server</button>
    </form>
    <form id="form2" action="">
        <input id="m2" autocomplete="off" /><button>Broadcast</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 socket = io();

        socket.on('pingReply', function (msg) {
            $('#messages').append($('<li>').text(msg));
        });

        socket.on('serverBroadcast', function (msg) {
            $('#messages').append($('<li>').text(msg));
        });

        $('#form1').submit(function () {

            socket.emit('ping', $('#m').val());
            $('#m').val('');
            return false;
        });

        $('#form2').submit(function () {

            socket.emit('broadcast', $('#m2').val());
            $('#m2').val('');
            return false;
        });
    </script>
</body>

</html>

reference:

No comments:

Post a Comment