websocket

package main

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

func main() {
    server, err := socketio.NewServer(nil)
    if err != nil {
        log.Fatal(err)
    }
    server.OnConnect("/", func(s socketio.Conn) error {
        s.SetContext("")
        fmt.Println("connected:", s.ID())
        return nil
    })
    server.OnEvent("/", "notice", func(s socketio.Conn, msg string) {
        fmt.Println("notice:", msg)
        s.Emit("reply", "have "+msg)
    })
    server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string {
        s.SetContext(msg)
        fmt.Println("msg="+msg);
        return "recv " + msg
    })
    server.OnEvent("/", "bye", func(s socketio.Conn) string {
        last := s.Context().(string)
        fmt.Println(last)
        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("closed", reason)
    })
    go server.Serve()
    defer server.Close()

    http.Handle("/socket.io/", server)
    var s=http.Dir("../asset")
    fmt.Println(s)
    //http.Handle("/file", http.FileServer(http.Dir("/files")))
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
    log.Println("Serving at localhost:8000...")
    log.Fatal(http.ListenAndServe(":8000", nil))
}
原文地址:https://www.cnblogs.com/tinaluo/p/13651196.html