Skip to content

Instantly share code, notes, and snippets.

@codeslinger
Forked from aaronfeng/test.go
Last active August 29, 2015 14:00
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 codeslinger/ebc006b6d76dc4fb0203 to your computer and use it in GitHub Desktop.
Save codeslinger/ebc006b6d76dc4fb0203 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net"
"bufio"
"io"
"os"
"time"
)
func bind(port string) {
ln, err := net.Listen("tcp", ":" + port)
if err != nil {
panic("Unable to listen to port: " + port)
}
fmt.Println("Listening on port: " + port)
for {
conn, err := ln.Accept()
if err != nil {
panic("Unable to accept connection on port: " + port)
}
fmt.Printf("%v <-> %v\n", conn.LocalAddr(), conn.RemoteAddr())
go handleConnection(conn)
}
}
func connect(port string) {
fmt.Printf("Connecting to: %s\n", port)
conn, err := net.Dial("tcp", ":" + port)
if err != nil {
fmt.Println(err)
return
}
handleConnection(conn)
}
func handleConnection(conn net.Conn) {
defer conn.Close()
b := bufio.NewReader(conn)
for {
line, err := b.ReadBytes('\n')
if err == io.EOF {
fmt.Printf("Client %v disconnected\n", conn.RemoteAddr())
return
} else {
conn.Write(line)
}
}
}
func main() {
go bind(os.Args[1])
connect(os.Args[2])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment