Created
April 30, 2014 01:28
-
-
Save aaronfeng/2a7d68e873bdbe22ce22 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 ( | |
"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