forked from dop251/goja
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udp.go
70 lines (60 loc) · 1.48 KB
/
udp.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
package socket
import (
"net"
"github.com/kmcsr/goja"
"github.com/kmcsr/goja/extern/events"
)
type UDPConn struct{
*events.EventEmitter
conn *net.UDPConn
runtime *goja.Runtime
Local goja.Value
Remote goja.Value
}
func wrapUDPConn(runtime *goja.Runtime, conn *net.UDPConn)(v goja.Value){
c := &UDPConn{
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(){
var (
buf = make([]byte, 1024 * 32)
)
for {
n, addr, err := conn.ReadFromUDP(buf)
if err != nil {
c.EmitAsync("error", c.runtime.ToValue(err))
return
}
c.EmitAsync("data", c.runtime.ToValue(buf[:n]), c.runtime.ToValue(addr.String()))
}
}()
return
}
func (c *UDPConn)Close(){
if err := c.conn.Close(); err != nil {
c.EmitAsync("error", c.runtime.ToValue(err))
panic(c.runtime.NewGoError(err))
}
}
func (c *UDPConn)Send(buf []byte){
if _, err := c.conn.Write(buf); err != nil {
c.EmitAsync("error", c.runtime.ToValue(err))
panic(c.runtime.NewGoError(err))
}
}
func (c *UDPConn)SendTo(buf []byte, addr string){
adr, err := net.ResolveUDPAddr(c.conn.LocalAddr().Network(), addr)
if err != nil {
c.EmitAsync("error", c.runtime.ToValue(err))
panic(c.runtime.NewGoError(err))
}
if _, err := c.conn.WriteToUDP(buf, adr); err != nil {
c.EmitAsync("error", c.runtime.ToValue(err))
panic(c.runtime.NewGoError(err))
}
}