-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebSockExample.fan
54 lines (46 loc) · 1.17 KB
/
WebSockExample.fan
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
using fwt
using gfx
using afWebSockets
using afConcurrent
using concurrent
@Js @NoDoc
class WebSockExample {
Void main() {
webSock := WebSocket().open(`ws://localhost:8069/ws`)
convBox := Text { text = "The conversation:\r\n"; multiLine = true; editable = false }
textBox := Text { text = "Say something!" }
sendMsg := |Event e| {
webSock.sendText(textBox.text)
textBox.text = ""
}
webSock.onMessage = |MsgEvent msgEnv| {
convBox.text += "\r\n" + msgEnv.msg
}
textBox.onAction.add(sendMsg)
window := Window {
title = "WebSocket ChatBox Example"
InsetPane {
EdgePane {
center = convBox
bottom = EdgePane {
center = textBox
right = Button { text = "Send"; onAction.add(sendMsg) }
}
},
},
}
if (Env.cur.runtime != "js") {
// ensure event funcs are run in the UI thread
safeMess := Unsafe(webSock.onMessage)
webSock.onMessage = |MsgEvent msgEnv| {
Desktop.callAsync |->| { safeMess.val->call(msgEnv) }
}
// call the blocking read() method in a background thread
safeSock := Unsafe(webSock)
Synchronized(ActorPool()).async |->| {
safeSock.val->read
}
}
window.open
}
}