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.io/engine.io implementation in Go

License

NotificationsYou must be signed in to change notification settings

zyxar/socketio

Repository files navigation

socket.io/engine.io implementation in Go

GoDocGo Report CardlicenseBuild Status

Install

go get -v -u github.com/zyxar/socketio

Features

  • compatible with official nodejs implementation (w/o room);
  • socket.io server;
  • socket.io client (websocket only);
  • engine.io server;
  • engine.io client (websocket only);
  • binary data;
  • namespace support;
  • socket.io-msgpack-parser support;

Example

Server:

package mainimport ("log""net/http""time""github.com/zyxar/socketio")funcmain() {server,_:=socketio.NewServer(time.Second*25,time.Second*5,socketio.DefaultParser)server.Namespace("/").OnConnect(func(so socketio.Socket) {log.Println("connected:",so.RemoteAddr(),so.Sid(),so.Namespace())}).OnDisconnect(func(so socketio.Socket) {log.Printf("%v %v %q disconnected",so.Sid(),so.RemoteAddr(),so.Namespace())}).OnError(func(so socketio.Socket,err...interface{}) {log.Println("socket",so.Sid(),so.RemoteAddr(),so.Namespace(),"error:",err)}).OnEvent("message",func(so socketio.Socket,datastring) {log.Println(data)})http.ListenAndServe(":8081",server)}

Client:

constio=require('socket.io-client');constsocket=io('http://localhost:8081');varid;socket.on('connect',function(){console.log('connected');if(id===undefined){id=setInterval(function(){socket.emit('message','hello there!')},2000);}});socket.on('event',console.log);socket.on('disconnect',function(){console.log('disconnected');if(id){clearInterval(id);id=undefined;}});

With Acknowledgements

  • Server -> Client

Server:

so.Emit("ack","foo",func(msgstring) {log.Println(msg)})

Client:

socket.on('ack',function(name,fn){console.log(name);fn('bar');})
  • Client -> Server

Server:

server.Namespace("/").OnEvent("foobar",func(datastring) (string,string) {log.Println("foobar:",data)return"foo","bar"})

Client:

socket.emit('foobar','-wow-',function(foo,bar){console.log('foobar:',foo,bar);});

With Binary Data

Server:

server.Namespace("/").OnEvent("binary",func(datainterface{},b*socketio.Bytes) {log.Println(data)bb,_:=b.MarshalBinary()log.Printf("%x",bb)}).OnConnect(func(so socketio.Socket) {gofunc() {for {select {case<-time.After(time.Second*2):iferr:=so.Emit("event","check it out!",time.Now());err!=nil {log.Println(err)return}}}}()})

Client:

varab=newArrayBuffer(4);vara=newUint8Array(ab);a.set([1,2,3,4]);id=setInterval(function(){socket.emit('binary','buf:',ab);},2000);socket.on('event',console.log);

Binary Helper forprotobuf

import ("github.com/golang/protobuf/proto")typeProtoMessagestruct {proto.Message}func (pProtoMessage)MarshalBinary() ([]byte,error) {returnproto.Marshal(p.Message)}func (p*ProtoMessage)UnmarshalBinary(b []byte)error {returnproto.Unmarshal(b,p.Message)}

Binary Helper forMessagePack

import ("github.com/tinylib/msgp/msgp")typeMessagePackstruct {Messageinterface {msgp.MarshalSizermsgp.Unmarshaler}}func (mMessagePack)MarshalBinary() ([]byte,error) {returnm.Message.MarshalMsg(nil)}func (m*MessagePack)UnmarshalBinary(b []byte)error {_,err:=m.Message.UnmarshalMsg(b)returnerr}

Customized Namespace

Server:

server.Namespace("/ditto").OnEvent("disguise",func(msginterface{},b socketio.Bytes) {bb,_:=b.MarshalBinary()log.Printf("%v: %x",msg,bb)})

Client:

letditto=io('http://localhost:8081/ditto');ditto.emit('disguise','pidgey',newArrayBuffer(8));

Parser

Theencoder anddecoder provided bysocketio.DefaultParser is compatible withsocket.io-parser, complying with revision 4 ofsocket.io-protocol.

AnEvent orAck Packet with any data satisfyingsocketio.Binary interface (e.g.socketio.Bytes) would be encoded asBinaryEvent orBinaryAck Packet respectively.

socketio.MsgpackParser, compatible withsocket.io-msgpack-parser, is an alternative custom parser.

nginx as Reverse Proxy (or TLS Terminator)

upstream socketio {    ip_hash;    server localhost:8080;}server {    # ...    location /socket.io/ {        if ($request_method = OPTIONS) {                add_header Content-Length 0;                add_header Content-Type text/plain;                add_header Access-Control-Allow-Origin "$http_origin" always;                add_header Access-Control-Allow-Credentials 'true' always;                add_header Access-Control-Allow-Methods "POST,GET,OPTIONS";                add_header Access-Control-Allow-Headers "content-type";                return 204;        }        proxy_pass http://socketio;        proxy_set_header Upgrade $http_upgrade;        proxy_set_header Connection "upgrade";        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        proxy_set_header Host $host;        add_header Access-Control-Allow-Origin "$http_origin" always;        add_header Access-Control-Allow-Credentials 'true' always;    }}

[8]ページ先頭

©2009-2025 Movatter.jp