/
clientreceive.go
105 lines (98 loc) · 2.34 KB
/
clientreceive.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package gluasocket_socketcore
import (
"bytes"
"io"
"net"
"time"
"github.com/yuin/gopher-lua"
)
func clientReceiveMethod(L *lua.LState) int {
client := checkClient(L)
pattern := L.Get(2)
//prefix := "" // TODO L.CheckString(3)
// Read a number of bytes from the socket
if pattern.Type() == lua.LTNumber {
if client.Timeout <= 0 {
client.Conn.SetDeadline(time.Time{})
} else {
client.Conn.SetDeadline(time.Now().Add(client.Timeout))
}
var buf bytes.Buffer
bytesToRead := L.ToInt(2)
for i := 0; i < bytesToRead; i++ {
byte, err := client.Reader.ReadByte()
if err == io.EOF {
break
}
if err != nil {
errstr := err.Error()
if err, ok := err.(net.Error); ok && err.Timeout() {
errstr = "timeout"
}
L.Push(lua.LNil)
L.Push(lua.LString(errstr))
return 2
}
buf.WriteByte(byte)
}
L.Push(lua.LString(string(buf.Bytes())))
return 1
}
// Read a line of text from the socket. Line separators are not returned.
// This is the default pattern so nil is the same as "*l".
if pattern.Type() == lua.LTNil || (pattern.Type() == lua.LTString && pattern.String() == "*l") {
var buf bytes.Buffer
for {
if client.Timeout <= 0 {
client.Conn.SetDeadline(time.Time{})
} else {
client.Conn.SetDeadline(time.Now().Add(client.Timeout))
}
line, isPrefix, err := client.Reader.ReadLine()
if err != nil {
errstr := err.Error()
if err, ok := err.(net.Error); ok && err.Timeout() {
errstr = "timeout"
}
L.Push(lua.LNil)
L.Push(lua.LString(errstr))
return 2
}
buf.Write(line)
if !isPrefix {
break
}
}
L.Push(lua.LString(string(buf.Bytes())))
return 1
}
// Read until the connection is closed
if pattern.Type() == lua.LTString && pattern.String() == "*a" {
if client.Timeout <= 0 {
client.Conn.SetDeadline(time.Time{})
} else {
client.Conn.SetDeadline(time.Now().Add(client.Timeout))
}
var buf bytes.Buffer
for {
byte, err := client.Reader.ReadByte()
if err == io.EOF {
break
}
if err != nil {
errstr := err.Error()
if err, ok := err.(net.Error); ok && err.Timeout() {
errstr = "timeout"
}
L.Push(lua.LNil)
L.Push(lua.LString(errstr))
return 2
}
buf.WriteByte(byte)
}
L.Push(lua.LString(string(buf.Bytes())))
return 1
}
L.RaiseError("client:receive() not implemented yet")
return 0
}