forked from dop251/goja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
93 lines (79 loc) · 1.7 KB
/
tcp.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
package socket
import (
"net"
"github.com/kmcsr/goja"
"github.com/kmcsr/goja/extern/events"
)
type TCPConn struct{
*events.EventEmitter
conn *net.TCPConn
runtime *goja.Runtime
Local goja.Value
Remote goja.Value
}
func wrapTCPConn(runtime *goja.Runtime, conn *net.TCPConn)(v goja.Value){
c := &TCPConn{
EventEmitter: events.NewEventEmitter(runtime),
conn: conn,
runtime: runtime,
Local: runtime.ToValue(conn.LocalAddr().String()),
Remote: runtime.ToValue(conn.RemoteAddr().String()),
}
v = runtime.ToValue(c)
go func(){
defer c.EmitAsync("close")
var (
buf = make([]byte, 1024 * 32)
)
for {
n, err := conn.Read(buf)
if err != nil {
c.EmitAsync("error", c.runtime.ToValue(err))
return
}
c.EmitAsync("data", c.runtime.ToValue(buf[:n]))
}
}()
return
}
func (c *TCPConn)Close(){
if err := c.conn.Close(); err != nil {
panic(c.runtime.NewGoError(err))
}
}
func (c *TCPConn)Send(buf []byte){
if _, err := c.conn.Write(buf); err != nil {
panic(c.runtime.NewGoError(err))
}
}
type TCPListener struct{
*events.EventEmitter
listener *net.TCPListener
runtime *goja.Runtime
Addr goja.Value
}
func wrapTCPListener(runtime *goja.Runtime, listener *net.TCPListener)(v goja.Value){
l := &TCPListener{
EventEmitter: events.NewEventEmitter(runtime),
listener: listener,
runtime: runtime,
Addr: runtime.ToValue(listener.Addr().String()),
}
v = runtime.ToValue(l)
go func(){
for {
conn, err := l.listener.AcceptTCP()
if err != nil {
return
}
c := wrapTCPConn(l.runtime, conn)
l.EmitAsync("accept", c)
}
}()
return
}
func (l *TCPListener)Close(a interface{}){
if err := l.listener.Close(); err != nil {
panic(l.runtime.NewGoError(err))
}
}