Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
/socket.ioPublic template

socket.io for golang, Start your pleasant journey! Support Socket.IO v4+😀

License

NotificationsYou must be signed in to change notification settings

zishang520/socket.io

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build StatusGoDoc

Features

Socket.IO enables real-time bidirectional event-based communication. It consists of:

  • Support Socket.IO v4+ 🚀🚀🚀
  • a Golang server (this repository)
  • aJavascript client library for the browser (or a Node.js client)

Some implementations in other languages are also available:

Its main features are:

Reliability

Connections are established even in the presence of:

  • proxies and load balancers.
  • personal firewall and antivirus software.

For this purpose, it relies onEngine.IO for golang, which first establishes a long-polling connection, then tries to upgrade to better transports that are "tested" on the side, like WebSocket. Please see theGoals section for more information.

Auto-reconnection support

Unless instructed otherwise a disconnected client will try to reconnect forever, until the server is available again. Please see the available reconnection optionshere.

Disconnection detection

A heartbeat mechanism is implemented at the Engine.IO level, allowing both the server and the client to know when the other one is not responding anymore.

That functionality is achieved with timers set on both the server and the client, with timeout values (thepingInterval andpingTimeout parameters) shared during the connection handshake. Those timers require any subsequent client calls to be directed to the same server, hence thesticky-session requirement when using multiples nodes.

Binary support

Any serializable data structures can be emitted, including:

  • []byte andio.Reader

Simple and convenient API

Sample code:

import ("github.com/zishang520/socket.io/v2/socket")io.On("connection",func(clients...any) {client:=clients[0].(*socket.Socket)client.Emit("request"/* … */)// emit an event to the socketio.Emit("broadcast"/* … */)// emit an event to all connected socketsclient.On("reply",func(...any) {/* … */ })// listen to the event})

Multiplexing support

In order to create separation of concerns within your application (for example per module, or based on permissions), Socket.IO allows you to create severalNamespaces, which will act as separate communication channels but will share the same underlying connection.

Room support

Within eachNamespace, you can define arbitrary channels, calledRooms, that sockets can join and leave. You can then broadcast to any given room, reaching every socket that has joined it.

This is a useful feature to send notifications to a group of users, or to a given user connected on several devices for example.

Note: Socket.IO is not a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the ack id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server (likews://echo.websocket.org) either. Please see the protocol specificationhere.

How to use

The following example attaches socket.io to a plain engine.io *types.CreateServer listening on port3000.

package mainimport ("github.com/zishang520/engine.io/v2/types""github.com/zishang520/engine.io/v2/utils""github.com/zishang520/socket.io/v2/socket""os""os/signal""syscall")funcmain() {httpServer:=types.CreateServer(nil)io:=socket.NewServer(httpServer,nil)io.On("connection",func(clients...any) {client:=clients[0].(*socket.Socket)client.On("event",func(datas...any) {        })client.On("disconnect",func(...any) {        })    })httpServer.Listen("127.0.0.1:3000",nil)exit:=make(chanstruct{})SignalC:=make(chan os.Signal)signal.Notify(SignalC,os.Interrupt,syscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT)gofunc() {fors:=rangeSignalC {switchs {caseos.Interrupt,syscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT:close(exit)return            }        }    }()<-exithttpServer.Close(nil)os.Exit(0)}

other: Usehttp.Handler interface

package mainimport ("net/http""os""os/signal""syscall""github.com/zishang520/socket.io/v2/socket")funcmain() {io:=socket.NewServer(nil,nil)http.Handle("/socket.io/",io.ServeHandler(nil))gohttp.ListenAndServe(":3000",nil)io.On("connection",func(clients...any) {client:=clients[0].(*socket.Socket)client.On("event",func(datas...any) {        })client.On("disconnect",func(...any) {        })    })exit:=make(chanstruct{})SignalC:=make(chan os.Signal)signal.Notify(SignalC,os.Interrupt,syscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT)gofunc() {fors:=rangeSignalC {switchs {caseos.Interrupt,syscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT:close(exit)return            }        }    }()<-exitio.Close(nil)os.Exit(0)}

other: Use fasthttp (fasthttp version 1.56.0+ is required)

package mainimport ("os""os/signal""syscall""time""github.com/valyala/fasthttp""github.com/valyala/fasthttp/fasthttpadaptor""github.com/zishang520/engine.io/v2/log""github.com/zishang520/engine.io/v2/types""github.com/zishang520/socket.io/v2/socket")funcmain() {log.DEBUG=truec:=socket.DefaultServerOptions()c.SetServeClient(true)// c.SetConnectionStateRecovery(&socket.ConnectionStateRecovery{})// c.SetAllowEIO3(true)c.SetPingInterval(300*time.Millisecond)c.SetPingTimeout(200*time.Millisecond)c.SetMaxHttpBufferSize(1000000)c.SetConnectTimeout(1000*time.Millisecond)c.SetCors(&types.Cors{Origin:"*",Credentials:true,    })socketio:=socket.NewServer(nil,nil)socketio.On("connection",func(clients...interface{}) {client:=clients[0].(*socket.Socket)client.On("message",func(args...interface{}) {client.Emit("message-back",args...)        })client.Emit("auth",client.Handshake().Auth)client.On("message-with-ack",func(args...interface{}) {ack:=args[len(args)-1].(socket.Ack)ack(args[:len(args)-1],nil)        })    })socketio.Of("/custom",nil).On("connection",func(clients...interface{}) {client:=clients[0].(*socket.Socket)client.Emit("auth",client.Handshake().Auth)    })gofasthttp.ListenAndServe(":3000",fasthttpadaptor.NewFastHTTPHandler(socketio.ServeHandler(c)))exit:=make(chanstruct{})SignalC:=make(chan os.Signal)signal.Notify(SignalC,syscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT)gofunc() {fors:=rangeSignalC {switchs {casesyscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT:close(exit)return            }        }    }()<-exitsocketio.Close(nil)os.Exit(0)}

other: Use fiber (fasthttp version 1.56.0+ is required)

package mainimport ("os""os/signal""syscall""time""github.com/gofiber/fiber/v2""github.com/gofiber/fiber/v2/middleware/adaptor""github.com/zishang520/engine.io/v2/log""github.com/zishang520/engine.io/v2/types""github.com/zishang520/socket.io/v2/socket")funcmain() {log.DEBUG=truec:=socket.DefaultServerOptions()c.SetServeClient(true)// c.SetConnectionStateRecovery(&socket.ConnectionStateRecovery{})// c.SetAllowEIO3(true)c.SetPingInterval(300*time.Millisecond)c.SetPingTimeout(200*time.Millisecond)c.SetMaxHttpBufferSize(1000000)c.SetConnectTimeout(1000*time.Millisecond)c.SetCors(&types.Cors{Origin:"*",Credentials:true,    })socketio:=socket.NewServer(nil,nil)socketio.On("connection",func(clients...interface{}) {client:=clients[0].(*socket.Socket)client.On("message",func(args...interface{}) {client.Emit("message-back",args...)        })client.Emit("auth",client.Handshake().Auth)client.On("message-with-ack",func(args...interface{}) {ack:=args[len(args)-1].(socket.Ack)ack(args[:len(args)-1],nil)        })    })socketio.Of("/custom",nil).On("connection",func(clients...interface{}) {client:=clients[0].(*socket.Socket)client.Emit("auth",client.Handshake().Auth)    })app:=fiber.New()// app.Put("/socket.io", adaptor.HTTPHandler(socketio.ServeHandler(c))) // testapp.Get("/socket.io",adaptor.HTTPHandler(socketio.ServeHandler(c)))app.Post("/socket.io",adaptor.HTTPHandler(socketio.ServeHandler(c)))goapp.Listen(":3000")exit:=make(chanstruct{})SignalC:=make(chan os.Signal)signal.Notify(SignalC,syscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT)gofunc() {fors:=rangeSignalC {switchs {casesyscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT:close(exit)return            }        }    }()<-exitsocketio.Close(nil)os.Exit(0)}

other: Use gin(Not necessary) + webtransport

package mainimport ("net/http""os""os/signal""syscall""time""github.com/gin-gonic/gin""github.com/zishang520/engine.io/v2/engine""github.com/zishang520/engine.io/v2/log""github.com/zishang520/engine.io/v2/types""github.com/zishang520/engine.io/v2/webtransport""github.com/zishang520/socket.io/v2/socket")funcmain() {log.DEBUG=truec:=socket.DefaultServerOptions()c.SetServeClient(true)// c.SetConnectionStateRecovery(&socket.ConnectionStateRecovery{})// c.SetAllowEIO3(true)c.SetPingInterval(300*time.Millisecond)c.SetPingTimeout(200*time.Millisecond)c.SetMaxHttpBufferSize(1000000)c.SetConnectTimeout(1000*time.Millisecond)c.SetTransports(types.NewSet("polling","webtransport"))c.SetCors(&types.Cors{Origin:"*",Credentials:true,    })socketio:=socket.NewServer(nil,nil)socketio.On("connection",func(clients...interface{}) {client:=clients[0].(*socket.Socket)client.On("message",func(args...interface{}) {client.Emit("message-back",args...)        })client.Emit("auth",client.Handshake().Auth)client.On("message-with-ack",func(args...interface{}) {ack:=args[len(args)-1].(socket.Ack)ack(args[:len(args)-1],nil)        })    })socketio.Of("/custom",nil).On("connection",func(clients...interface{}) {client:=clients[0].(*socket.Socket)client.Emit("auth",client.Handshake().Auth)    })app:=gin.Default()// app.Put("/socket.io", adaptor.HTTPHandler(socketio.ServeHandler(c))) // testapp.POST("/socket.io/*f",gin.WrapH(socketio.ServeHandler(c)))app.GET("/socket.io/*f",gin.WrapH(socketio.ServeHandler(c)))goapp.Run(":8080")// WebTransport start// WebTransport uses udp, so you need to enable the new service.customServer:=types.NewWebServer(nil)// A certificate is required and cannot be a self-signed certificate.wts:=customServer.ListenWebTransportTLS(":443","domain.cer","domain.key",nil,nil)// Here is the core logic of the WebTransport handshake.customServer.HandleFunc(socketio.Path()+"/",func(w http.ResponseWriter,r*http.Request) {ifwebtransport.IsWebTransportUpgrade(r) {// You need to call socketio.ServeHandler(nil) before this, otherwise you cannot get the Engine instance.socketio.Engine().(engine.Server).OnWebTransportSession(types.NewHttpContext(w,r),wts)        }else {customServer.DefaultHandler.ServeHTTP(w,r)        }    })// WebTransport endexit:=make(chanstruct{})SignalC:=make(chan os.Signal)signal.Notify(SignalC,syscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT)gofunc() {fors:=rangeSignalC {switchs {casesyscall.SIGHUP,syscall.SIGINT,syscall.SIGTERM,syscall.SIGQUIT:close(exit)return            }        }    }()<-exitsocketio.Close(nil)os.Exit(0)}

WebTransport client (js):

constmanager=newio.Manager("https://domain",{transports:['webtransport'],});constsocket=manager.socket("/",{reconnectionDelayMax:10000,auth:{token:"123"},query:{"my-key":"my-value"}});

Documentation

Please see the documentationhere.

Debug / logging

In order to see all the debug output, run your app with the environment variableDEBUG including the desired scope.

To see the output from all of Socket.IO's debugging scopes you can use:

DEBUG=socket.io*

Testing

make test

License

MIT


[8]ページ先頭

©2009-2025 Movatter.jp