-
-
Save codeslinger/ebc006b6d76dc4fb0203 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) { | |
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