Created
April 19, 2014 19:56
-
-
Save nikhan/11095595 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import( | |
"net" | |
"fmt" | |
"bufio" | |
"time" | |
) | |
var emit chan []byte | |
func handshake(conn net.Conn){ | |
reader := bufio.NewReader(conn) | |
conn.Write([]byte("identify")) | |
name, _ := reader.ReadString('\n') | |
conn.Write([]byte("hello " + name)) | |
} | |
func readLoop(conn net.Conn){ | |
reader := bufio.NewReader(conn) | |
for{ | |
line, err := reader.ReadString('\n') | |
if err != nil { | |
break | |
} | |
fmt.Printf(line) | |
} | |
fmt.Println("connection closed") | |
} | |
func writeLoop(conn net.Conn){ | |
writer := bufio.NewWriter(conn) | |
for{ | |
select{ | |
case msg := <- emit: | |
writer.Write(msg) | |
writer.Flush() | |
} | |
} | |
} | |
func heartbeat(conn net.Conn){ | |
tick := time.NewTicker(1 * time.Second) | |
for{ | |
select{ | |
case <- tick.C: | |
emit <- []byte("hearbeat") | |
} | |
} | |
} | |
func main(){ | |
ln, _ := net.Listen("tcp", ":8080") | |
emit = make(chan []byte) | |
for { | |
conn, _ := ln.Accept() | |
fmt.Println("new connection") | |
handshake(conn) | |
go readLoop(conn) | |
go writeLoop(conn) | |
go heartbeat(conn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment