multithreading - How to add multi-threading/multi-client feature to a very simple scala server program? -
scala newbie here,
i'm deliberately using older version of scala 2.7.5
this compatibilites older libraries need use along server code
val server = new serversocket(9999) println("server initialized:") val client = server.accept /* initalize big service here -> takes >10 seconds */ while(true){ val in = new bufferedreader(new inputstreamreader(client.getinputstream)).readline val out = new printstream(client.getoutputstream) println("server received:" + in) out.println("message received") out.flush }
basically, works single client. won't connect client because running inside while
loop
i need modify code process requests multiple clients
therefore, possible me without writing multithreaded program?
if not, can me out code snippet add basic threading program?
you'll want use nio channels
in non-blocking mode - let multiplex several input streams using single thread. this tutorial in nio socketchannel along explanation of how switch non-blocking mode, , this tutorial on using selectors same author. socketchannel you'll use read sockets, , selector you'll use multiplex channels.
from tutorial linked above:
socketchannel socketchannel = socketchannel.open(); socketchannel.configureblocking(false); socketchannel.connect(new inetsocketaddress("http://jenkov.com", 80)); while(! socketchannel.finishconnect() ){ //wait, or else... }
calling read
on non-blocking socketchannel
might return 0 bytes, check see how many bytes returned.
as selector
(again tutorial)
selector selector = selector.open(); // op_read means selector interested in read events selectionkey key1 = socketchannel1.register(selector, selectionkey.op_read); selectionkey key2 = socketchannel2.register(selector, selectionkey.op_read); iterator<selectionkey> keyiterator = selector.selectedkeys().iterator(); while(keyiterator.hasnext()) { selectionkey key = keyiterator.next(); if (key.isreadable()) { // read channel } }
Comments
Post a Comment