Skip to content

Instantly share code, notes, and snippets.

@fanzeyi
Created July 5, 2016 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fanzeyi/0cf64af918ffee0ef9a62f865257e44d to your computer and use it in GitHub Desktop.
Save fanzeyi/0cf64af918ffee0ef9a62f865257e44d to your computer and use it in GitHub Desktop.
A simple TCP echo server for Chrome's native messaging
package main
import (
"fmt"
"os"
"net"
"bufio"
"encoding/binary"
)
const (
HOST = "localhost"
PORT = "8888"
TYPE = "tcp"
)
func main() {
l, err := net.Listen(TYPE, HOST + ":" + PORT)
if err != nil {
fmt.Fprintln(os.Stderr, "Error Listening: ", err.Error())
os.Exit(1)
}
defer l.Close()
//fmt.Println("Listening on " + HOST + ":" + PORT)
ch := make(chan string)
connCh := make(chan net.Conn)
go readStdin(ch)
go handleStdin(ch, connCh)
for {
conn, err := l.Accept()
if err != nil {
fmt.Fprintln(os.Stderr, "Error accepting: ", err.Error())
}
connCh <- conn
go handleRequest(conn)
}
}
func readStdin(ch chan string) {
reader := bufio.NewReader(os.Stdin)
buffer := make([]byte, 1024)
for {
length, err := reader.Read(buffer)
if err != nil {
close(ch)
return
}
ch <- string(buffer[4:length])
}
close(ch)
}
func handleStdin(ch chan string, connCh chan net.Conn) {
conns := make([]net.Conn, 8)
stdinLoop:
for {
select {
case stdin, ok := <-ch:
if !ok {
break stdinLoop
} else {
bytes := []byte(stdin)
for _, conn := range conns {
if conn != nil {
conn.Write(bytes)
}
}
}
case conn, ok := <-connCh:
if !ok {
} else {
conns = append(conns, conn)
}
}
}
}
func handleRequest(conn net.Conn) {
buffer := make([]byte, 1024)
for {
length, err := bufio.NewReader(conn).Read(buffer)
lengthByte := make([]byte, 4)
binary.LittleEndian.PutUint32(lengthByte, uint32(length))
if err != nil {
break
} else {
fmt.Print(string(lengthByte) + string(buffer[:length]))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment