Created
November 20, 2009 20:19
-
-
Save faried/239744 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"bufio"; | |
"fmt"; | |
"net"; | |
"os"; | |
) | |
var nl byte = 10; | |
func echo(conn *net.TCPConn) { | |
addr := conn.RemoteAddr(); | |
rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)); | |
for { | |
s, err := rw.ReadString(nl); | |
if len(s) > 0 { | |
fmt.Printf("conn %s said %d %s", addr, len(s), s); | |
rw.WriteString(s); | |
rw.Flush(); | |
} else if err == os.EOF { | |
fmt.Printf("conn %s eof\n", addr); | |
conn.Close(); | |
return; | |
} else { | |
fmt.Printf("error reading: %s\n", err.String()); | |
conn.Close(); | |
return; | |
} | |
if s == "quit\r\n" { | |
conn.Close(); | |
return; | |
} | |
} | |
} | |
func main() { | |
l, err := net.ListenTCP("tcp4", &net.TCPAddr{net.IPv4zero, 3080}); | |
if l == nil { | |
fmt.Printf("cannot listen: %s\n", err.String()); | |
os.Exit(1); | |
} | |
fmt.Printf("listening at %s\n", l.Addr()); | |
for { | |
conn, err := l.AcceptTCP(); | |
if conn == nil { | |
fmt.Printf("accept error: %s\n", err.String()); | |
l.Close(); | |
os.Exit(1); | |
} | |
fmt.Printf("connection from %s\n", conn.RemoteAddr()); | |
go echo(conn); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment