Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
42
Task/Chat-server/Nim/chat-server.nim
Normal file
42
Task/Chat-server/Nim/chat-server.nim
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import asyncnet, asyncdispatch
|
||||
|
||||
type
|
||||
Client = tuple
|
||||
socket: AsyncSocket
|
||||
name: string
|
||||
connected: bool
|
||||
|
||||
var clients {.threadvar.}: seq[Client]
|
||||
|
||||
proc sendOthers(client: Client, line: string) {.async.} =
|
||||
for c in clients:
|
||||
if c != client and c.connected:
|
||||
await c.socket.send(line & "\c\L")
|
||||
|
||||
proc processClient(socket: AsyncSocket) {.async.} =
|
||||
await socket.send("Please enter your name: ")
|
||||
var client: Client = (socket, await socket.recvLine(), true)
|
||||
|
||||
clients.add(client)
|
||||
asyncCheck client.sendOthers("+++ " & client.name & " arrived +++")
|
||||
|
||||
while true:
|
||||
let line = await client.socket.recvLine()
|
||||
if line == "":
|
||||
asyncCheck client.sendOthers("--- " & client.name & " leaves ---")
|
||||
client.connected = false
|
||||
return
|
||||
asyncCheck client.sendOthers(client.name & "> " & line)
|
||||
|
||||
proc serve() {.async.} =
|
||||
clients = @[]
|
||||
var server = newAsyncSocket()
|
||||
server.bindAddr(Port(4004))
|
||||
server.listen()
|
||||
|
||||
while true:
|
||||
let socket = await server.accept()
|
||||
asyncCheck processClient(socket)
|
||||
|
||||
asyncCheck serve()
|
||||
runForever()
|
||||
Loading…
Add table
Add a link
Reference in a new issue