-
Notifications
You must be signed in to change notification settings - Fork 11
/
chatserver.nim
41 lines (32 loc) · 1.04 KB
/
chatserver.nim
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
import asyncnet, asyncdispatch
type Client = tuple[socket: AsyncSocket, name: string]
var clients: seq[Client] = @[]
proc sendOthers(client: Client, line: string) {.async.} =
for c in clients:
if c != client:
await c.socket.send(line & "\c\L")
proc processClient(socket: AsyncSocket) {.async.} =
await socket.send("Please enter your name: ")
let client: Client = (socket, await socket.recvLine())
clients.add client
discard client.sendOthers "+++ " & client.name & " arrived +++"
while true:
let line = await client.socket.recvLine()
if line == "":
discard client.sendOthers "--- " & client.name & " leaves ---"
break
discard client.sendOthers client.name & "> " & line
for i,c in clients:
if c == client:
clients.del i
break
proc serve {.async.} =
var server = newAsyncSocket()
server.setSockOpt(OptReuseAddr, true)
server.bindAddr(Port(4004))
server.listen()
while true:
let socket = await server.accept()
discard processClient socket
asyncCheck serve()
runForever()