Skip to content

Instantly share code, notes, and snippets.

@dthtvwls
Last active May 17, 2017 14:18
Show Gist options
  • Save dthtvwls/59162132085197104e8649f293710d24 to your computer and use it in GitHub Desktop.
Save dthtvwls/59162132085197104e8649f293710d24 to your computer and use it in GitHub Desktop.
Ask if a word is in the dictionary via TCP
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"strconv"
"strings"
"unicode"
)
var dict = make(map[string]bool, 0)
func init() {
if file, err := os.Open("/usr/share/dict/words"); err != nil {
log.Fatalln(err)
} else {
defer file.Close()
scanner := bufio.NewScanner(file)
SCAN:
for scanner.Scan() {
word := scanner.Text()
if unicode.IsUpper(rune(word[0])) {
continue
}
for _, letter := range word {
if !unicode.IsLetter(letter) {
continue SCAN
}
}
dict[word] = true
}
}
flag.Parse()
}
func main() {
if ln, err := net.Listen("tcp", flag.Arg(0)); err != nil {
log.Fatalln(err)
} else {
defer ln.Close()
for {
if conn, err := ln.Accept(); err != nil {
log.Println(err)
} else {
go func() {
defer conn.Close()
if message, err := ioutil.ReadAll(bufio.NewReader(conn)); err != nil {
log.Println(err)
} else {
conn.Write([]byte(strconv.FormatBool(dict[strings.TrimSpace(string(message))])))
}
}()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment