golang-socketio/send.go

89 lines
1.6 KiB
Go
Raw Normal View History

2016-05-18 22:11:10 +02:00
package gosocketio
import (
"encoding/json"
"errors"
2017-03-15 14:30:36 +01:00
"log"
"time"
"forge.cadoles.com/Pyxis/golang-socketio/protocol"
2016-05-18 22:11:10 +02:00
)
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 {
2017-03-15 14:30:36 +01:00
//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
}
2016-05-18 22:11:10 +02:00
msg.Args = string(json)
}
2016-05-18 22:11:10 +02:00
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{
2017-03-15 14:30:36 +01:00
Type: protocol.MessageTypeEmit,
Method: method,
2016-05-18 22:11:10 +02:00
}
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{
2017-03-15 14:30:36 +01:00
Type: protocol.MessageTypeAckRequest,
AckId: c.ack.getNextId(),
Method: method,
2016-05-18 22:11:10 +02:00
}
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
}
}