Skip to content

Instantly share code, notes, and snippets.

@maasg
Last active August 15, 2017 19:39
Show Gist options
  • Save maasg/af43502c7c9d5b08199f0015a8404486 to your computer and use it in GitHub Desktop.
Save maasg/af43502c7c9d5b08199f0015a8404486 to your computer and use it in GitHub Desktop.
Simple TCP server delivering random words from a predefined dictionary
package so
import java.io.PrintStream
import java.net.Socket
import java.net._
import scala.concurrent.Future
class SocketHandler(socket: Socket) {
def deliver(data: Iterator[String]): Unit = {
val out = new PrintStream(socket.getOutputStream())
for (d <- data) {
out.println(d)
out.flush()
Thread.sleep(500)
}
}
}
case class RandomWordIterator(dict: Array[String]) extends Iterable[String] {
val elems = dict.size
override def iterator: Iterator[String] = new Iterator[String]() {
override def hasNext: Boolean = true
override def next(): String = dict(scala.util.Random.nextInt(elems))
}
}
object SimpleTCPServer {
import scala.concurrent.ExecutionContext.Implicits.global
def accept(server: ServerSocket): Unit = {
val s = server.accept()
Future {
new SocketHandler(s).deliver(RandomWordIterator(words).iterator)
}
accept(server)
}
def main(args: Array[String]): Unit = {
val port = 9999
println(s"Ready to receive on port: $port")
accept(new ServerSocket(port))
}
// source for the word list: http://www.ef.com/english-resources/english-vocabulary/top-3000-words/
val words ="""
|abandon, ability, able, abortion, about, above, abroad, absence, absolute, absolutely, absorb, abuse, academic,
|accept, access, accident, accompany, accomplish, according, account, accurate, accuse, achieve, achievement, acid,
|acknowledge, acquire, across, act, action, active, activist, activity, actor, actress, actual, actually, ad, adapt,
|add, addition, additional, address, adequate, adjust, adjustment, administration, administrator, admire, admission,
|admit, adolescent, adopt, adult, advance, advanced, advantage, adventure, advertising, advice, advise, adviser,
|advocate, affair, affect, afford, afraid, African, African-American, after, afternoon, again, against, age, agency,
|agenda, agent, aggressive, ago, agree, agreement, agricultural, ah, ahead, aid, aide, AIDS, aim, air, aircraft,
|airline, airport, album, alcohol, alive, all, alliance, allow, ally, almost, alone, along, already, also, alter,
|alternative, although, always, AM, amazing, American, among, amount, analysis, analyst, analyze, ancient, and, anger,
|angle, angry, animal, anniversary, announce, annual, another, answer, anticipate, anxiety, any, anybody, anymore,
|anyone, anything, anyway, anywhere, apart, apartment, apparent, apparently, appeal, appear, appearance, apple,
|application, apply, appoint, appointment, appreciate, approach, appropriate, approval, approve, approximately, Arab,
|architect, area, argue, argument, arise, arm, armed, army, around, arrange, arrangement, arrest, arrival, arrive,
|art, article, artist, artistic, as, Asian, aside, ask, asleep, aspect, assault, assert, assess, assessment, asset,
|assign, assignment, assist, assistance, assistant, associate, association, assume, assumption, assure, at, athlete,
|athletic, atmosphere, attach, attack, attempt, attend, attention, attitude, attorney, attract, attractive, attribute,
|audience, author, authority, auto, available, average, avoid, award, aware, awareness, away, awful, baby, back,
|background, bad, badly, bag, bake, balance, ball, ban, band, bank, bar, barely, barrel, barrier, base, baseball,
|basic, basically, basis, basket, basketball, bathroom, battery, battle, be, beach, bean, bear, beat, beautiful,
|beauty, because, become, bed, bedroom, beer, before, begin, beginning, behavior, behind, being, belief, believe,
|bell, belong, below, belt, bench, bend, beneath, benefit, beside, besides, best, bet, better, between, beyond, Bible,
|big, bike, bill, billion, bind, biological, bird, birth, birthday, bit, bite, black, blade, blame, blanket, blind,
|block, blood, blow, blue, board, boat, body, bomb, bombing, bond, bone, book, boom, boot, border, born, borrow, boss,
|both, bother, bottle, bottom, boundary, bowl, box, boy, boyfriend, brain, branch, brand, bread, break, breakfast,
|breast, breath, breathe, brick, bridge, brief, briefly, bright, brilliant, bring, British, broad, broken, brother,
|brown, brush, buck, budget, build, building, bullet, bunch, burden, burn, bury, bus, business, busy, but, butter,
|button, buy, buyer, by, cabin, cabinet, cable, cake, calculate, call, camera, camp, campaign, campus, can, Canadian,
|cancer, candidate, cap, capability, capable, capacity, capital, captain, capture, car, carbon, card, care, career,
|careful, carefully, carrier, carry, case, cash, cast, cat, catch, category, Catholic, cause, ceiling, celebrate,
|celebration, celebrity, cell, center, central, century, CEO, ceremony, certain, certainly, chain, chair, chairman,
|challenge, chamber, champion, championship, chance, change, changing, channel, chapter, character, characteristic,
|characterize, charge, charity, chart, chase, cheap, check, cheek, cheese, chef, chemical, chest, chicken, chief,
|child, childhood, Chinese, chip, chocolate, choice, cholesterol, choose, Christian, Christmas, church, cigarette,
|circle, circumstance, cite, citizen, city, civil, civilian, claim, class, classic, classroom, clean, clear, clearly,
|client, climate, climb, clinic, clinical, clock, close, closely, closer, clothes, clothing, cloud
""".stripMargin.split(",").map(_.trim)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment