1 Star 0 Fork 0

574893508/golang-socketio

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
send.go 1.58 KB
一键复制 编辑 原始数据 按行查看 历史
Gennadii Kovalev 提交于 2017-03-15 15:30 . encoding/json panic recovery
package gosocketio
import (
"encoding/json"
"errors"
"github.com/graarh/golang-socketio/protocol"
"log"
"time"
)
var (
ErrorSendTimeout = errors.New("Timeout")
ErrorSocketOverflood = errors.New("Socket overflood")
)
/**
Send message packet to socket
*/
func send(msg *protocol.Message, c *Channel, args interface{}) error {
//preventing json/encoding "index out of range" panic
defer func() {
if r := recover(); r != nil {
log.Println("socket.io send panic: ", r)
}
}()
if args != nil {
json, err := json.Marshal(&args)
if err != nil {
return err
}
msg.Args = string(json)
}
command, err := protocol.Encode(msg)
if err != nil {
return err
}
if len(c.out) == queueBufferSize {
return ErrorSocketOverflood
}
c.out <- command
return nil
}
/**
Create packet based on given data and send it
*/
func (c *Channel) Emit(method string, args interface{}) error {
msg := &protocol.Message{
Type: protocol.MessageTypeEmit,
Method: method,
}
return send(msg, c, args)
}
/**
Create ack packet based on given data and send it and receive response
*/
func (c *Channel) Ack(method string, args interface{}, timeout time.Duration) (string, error) {
msg := &protocol.Message{
Type: protocol.MessageTypeAckRequest,
AckId: c.ack.getNextId(),
Method: method,
}
waiter := make(chan string)
c.ack.addWaiter(msg.AckId, waiter)
err := send(msg, c, args)
if err != nil {
c.ack.removeWaiter(msg.AckId)
}
select {
case result := <-waiter:
return result, nil
case <-time.After(timeout):
c.ack.removeWaiter(msg.AckId)
return "", ErrorSendTimeout
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zyl1221/golang-socketio.git
[email protected]:zyl1221/golang-socketio.git
zyl1221
golang-socketio
golang-socketio
master

搜索帮助