Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"net"
"bufio"
"io"
"os"
"time"
)
func bind(port string) chan net.Conn {
ch := make(chan net.Conn)
go func() {
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())
ch <- conn
}
}()
return ch
}
func connect(port string) chan net.Conn {
ch := make(chan net.Conn)
go func() {
fmt.Printf("Connecting to: %s\n", port)
conn, err := net.Dial("tcp", ":" + port)
if err != nil {
fmt.Println(err)
}
ch <- conn
}()
return ch
}
func handleConnection(conn net.Conn) {
b := bufio.NewReader(conn)
for {
line, err := b.ReadBytes('\n')
if err == io.EOF {
fmt.Printf("Client %v disconnected\n", conn.RemoteAddr())
conn.Close()
return
} else {
conn.Write(line)
}
}
}
func main() {
c1 := bind(os.Args[1])
time.Sleep(5 * time.Second)
c2 := connect(os.Args[2])
for {
go handleConnection(<-c1)
go handleConnection(<-c2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment