Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Nim非同期I/Oを使う

初めまして。
今回初めてAdventCalenderを書くにあたって、この辺から適当にサンプル引っ張って来ます。

Nim/tests/async

動作環境

  • Ubuntu 17.10
  • Nim 0.17.2

Module asyncfile

普通のファイル読み込みです。

readfile.nim
import asyncfile, asyncdispatch, os

const log = "/var/log/mylog"

proc main() {.async.} =
  let file = openAsync(log, fmRead)
  let data = await file.readAll()
  echo data
  file.close()

waitFor main()
nim c --hints:off -r readfile.nim

FutureStreamを使う場合です。
ただし、ファイル終端に達した時点で終了する模様で、追加されたのを検知できなようです。
FutureStreamの定義がどこにあるのかわからず

fsstream.nim
import asyncfile, asyncdispatch, os

const log = "/var/log/mylog"

proc main() {.async.} =
  var fs = newFutureStream[string]()
  let file = openAsync(log, fmRead)
  discard file.readToStream(fs)

  while not fs.finished:
    let (hasValue, value) = await fs.read()
    if hasValue:
      echo(value)

  file.close()
waitFor main()

AsyncSocketの使い方です。

AsyncNet

socket.nim
import asyncnet, asyncdispatch, streams, os, net

proc processClient(client: AsyncSocket) {.async.} =
  while true:
    let line = await client.recvLine()
    if line == "" or line == "\r\n":
      break

    echo line

proc serve() {.async.} =
  var server = newAsyncSocket()
  server.setSockOpt(OptReuseAddr, true)
  server.bindAddr(Port(8080))
  server.listen()

  while true:
    let client = await server.accept()
    asyncCheck processClient(client)

asyncCheck serve()
runForever()

以上です。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
5
Help us understand the problem. What are the problem?