Source

netserv / echo / echo_serv.go

Full commit
package main

import (
	"fmt"
	"net"
	"os"
)

func main() {
	go echoOnTCP()

	dummy := make(chan int)
	<-dummy
}

func echoOnTCP() {
	var err os.Error
	var addr *net.TCPAddr
	addr, err = net.ResolveTCPAddr("0.0.0.0:7")
	if err != nil {
		fmt.Fprintf(os.Stderr, "net.ResolveTCPAddr() failed: %v\n", err)
		os.Exit(1)
	}

	var listener *net.TCPListener
	listener, err = net.ListenTCP("tcp4", addr)
	if err != nil {
		fmt.Fprintf(os.Stderr, "net.ListenTCP() failed: %v\n", err)
		os.Exit(1)
	}

	for {
		var conn *net.TCPConn
		conn, err = listener.AcceptTCP()
		if err != nil {
			fmt.Fprintf(os.Stderr, "listener.AcceptTCP() failed: %v\n", err)
			fmt.Fprintf(os.Stderr, "Will continue on the next connection request.\n")
			continue
		}

		go processTCP(conn)
	}
}

func processTCP(conn *net.TCPConn) {
	for {
		var buf [4096]byte
		nread, err := conn.Read(&buf)
		if err != nil {
			fmt.Fprintf(os.Stderr, "conn.Read() failed: %v\n", err)
			break
		}

		_, err = conn.Write(buf[0:nread])
		if err != nil {
			fmt.Fprintf(os.Stderr, "conn.Write() failed: %v\n", err)
			break
		}
	}

	conn.Close()
}