RosettaCodeData/Task/Chat-server/Nim/chat-server.nim

43 lines
1 KiB
Nim
Raw Permalink Normal View History

2016-12-05 23:44:36 +01:00
import asyncnet, asyncdispatch
2017-09-23 10:01:46 +02:00
type
Client = tuple
socket: AsyncSocket
name: string
connected: bool
var clients {.threadvar.}: seq[Client]
2016-12-05 23:44:36 +01:00
proc sendOthers(client: Client, line: string) {.async.} =
for c in clients:
2017-09-23 10:01:46 +02:00
if c != client and c.connected:
2016-12-05 23:44:36 +01:00
await c.socket.send(line & "\c\L")
proc processClient(socket: AsyncSocket) {.async.} =
await socket.send("Please enter your name: ")
2017-09-23 10:01:46 +02:00
var client: Client = (socket, await socket.recvLine(), true)
2016-12-05 23:44:36 +01:00
2017-09-23 10:01:46 +02:00
clients.add(client)
asyncCheck client.sendOthers("+++ " & client.name & " arrived +++")
2016-12-05 23:44:36 +01:00
while true:
let line = await client.socket.recvLine()
if line == "":
2017-09-23 10:01:46 +02:00
asyncCheck client.sendOthers("--- " & client.name & " leaves ---")
client.connected = false
return
asyncCheck client.sendOthers(client.name & "> " & line)
2016-12-05 23:44:36 +01:00
proc serve() {.async.} =
2017-09-23 10:01:46 +02:00
clients = @[]
2016-12-05 23:44:36 +01:00
var server = newAsyncSocket()
server.bindAddr(Port(4004))
server.listen()
while true:
let socket = await server.accept()
2017-09-23 10:01:46 +02:00
asyncCheck processClient(socket)
2016-12-05 23:44:36 +01:00
2017-09-23 10:01:46 +02:00
asyncCheck serve()
2016-12-05 23:44:36 +01:00
runForever()