GO语言 --socket.io

Posted ⬆️小马哥⬆️

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GO语言 --socket.io相关的知识,希望对你有一定的参考价值。

socket.io是对websocket的封装以及扩展, 可以跨平台使用, 具体可看官网..

GO语言实现:

package main

import (
    "github.com/googollee/go-socket.io"
    "github.com/nicholaskh/log4go"
    "net/http"

    "os"
    "time"
    "path"
    "strings"
    "runtime"
    "fmt"
)
var gLogger log4go.Logger;


//do init before all others
func initAll(){
    gLogger = nil

    initLogger()
}

//de-init for all
func deinitAll(){
    if(nil == gLogger) {
        gLogger.Close();
        gLogger = nil
    }
}

func main()  {
    initAll()

    server, err := socketio.NewServer(nil)
    if err != nil {
        gLogger.Warn("启动服务器错误")
    }

    server.On("connection", func(so socketio.Socket) {
        gLogger.Info("on connection")
        so.Join("chat")
        so.On("chat message", func(msg string) {
            m := make(map[string]interface{})
            m["a"] = "你好"
            e := so.Emit("cn1111", m)
            //这个没有问题
            fmt.Println("\n\n")

            b := make(map[string]string)
            b["u-a"] = "中文内容" //这个不能是中文
            m["b-c"] = b
            e = so.Emit("cn2222", m)
            gLogger.Info(e)

            gLogger.Info("emit:", so.Emit("chat message", msg))
            so.BroadcastTo("chat", "chat message", msg)
        })
        // Socket.io acknowledgement example
        // The return type may vary depending on whether you will return
        // For this example it is "string" type
        so.On("chat message with ack", func(msg string) string {
            return msg
        })
        so.On("disconnection", func() {
            gLogger.Info("on disconnect")
        })

    })

    server.On("error", func(so socketio.Socket, err error) {
        gLogger.Warn("ERROR: ", err)
    })

    http.Handle("/socket.io/", server)
    http.Handle("/", http.FileServer(http.Dir("/Users/deer_mac/Downloads/go-socket.io-master/example/chat/Public")))
    gLogger.Info("Serving at localhost:5000...")
    http.ListenAndServe(":5000", nil)
    deinitAll()
}

// GetCurFilename
// Get current file name, without suffix
func GetCurFilename() string {
    _, fulleFilename, _, _ := runtime.Caller(0)
    //fmt.Println(fulleFilename)
    var filenameWithSuffix string
    filenameWithSuffix = path.Base(fulleFilename)
    //fmt.Println("filenameWithSuffix=", filenameWithSuffix)
    var fileSuffix string
    fileSuffix = path.Ext(filenameWithSuffix)
    //fmt.Println("fileSuffix=", fileSuffix)

    var filenameOnly string
    filenameOnly = strings.TrimSuffix(filenameWithSuffix, fileSuffix)
    //fmt.Println("filenameOnly=", filenameOnly)

    return filenameOnly
}

//init for logger
func initLogger(){
    var filenameOnly string
    filenameOnly = GetCurFilename()
    var logFilename string =  filenameOnly + ".log";

    //gLogger = log4go.NewLogger()
    gLogger = make(log4go.Logger)
    //for console
    //gLogger.AddFilter("stdout", log4go.INFO, log4go.NewConsoleLogWriter())
    gLogger.AddFilter("stdout", log4go.INFO, log4go.NewConsoleLogWriter())
    //for log file
    if _, err := os.Stat(logFilename); err == nil {
        //fmt.Printf("found old log file %s, now remove it\n", logFilename)
        os.Remove(logFilename)
    }
    //gLogger.AddFilter("logfile", log4go.FINEST, log4go.NewFileLogWriter(logFilename, true))
    gLogger.AddFilter("logfile", log4go.FINEST, log4go.NewFileLogWriter(logFilename, false))
    gLogger.Info("Current time is : %s", time.Now().Format("15:04:05 MST 2006/01/02"))

    return
}

 

以上是关于GO语言 --socket.io的主要内容,如果未能解决你的问题,请参考以下文章

Go语言学习——go语言介绍安装运行

Go语言学习之路

2021-GO语言并发编程

2021-GO语言并发编程

golang 目录

Go语言的应用