Last active
December 1, 2015 00:21
-
-
Save kvu787/218700608055ceb1cff3 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" | |
"os" | |
) | |
const Message string = "Hello World!\n" | |
const ServerPort string = "173.250.148.245" | |
func main() { | |
if len(os.Args) < 2 { | |
panic("not enough args") | |
} | |
if os.Args[1] == "server" { | |
server() | |
} else if os.Args[1] == "client" { | |
client() | |
} else { | |
panic("bad args") | |
} | |
} | |
func server() { | |
ln, err := net.Listen("tcp", ":80") | |
if err != nil { | |
panic(err) | |
} | |
for { | |
conn, err := ln.Accept() | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("local addr: %v\n", conn.LocalAddr()) | |
fmt.Printf("remote addr: %v\n", conn.RemoteAddr()) | |
bs := make([]byte, len(Message)) | |
n, err := conn.Read(bs) | |
if err != nil { | |
panic(err) | |
} | |
if n != len(Message) { | |
panic("not enough bytes read") | |
} | |
fmt.Printf("message received: %s\n", string(bs)) | |
err = conn.Close() | |
if err != nil { | |
panic(err) | |
} | |
} | |
} | |
func client() { | |
conn, err := net.Dial("tcp", ServerPort+":80") | |
if err != nil { | |
panic(err) | |
} | |
n, err := conn.Write([]byte(Message)) | |
if err != nil { | |
panic(err) | |
} | |
if n != len(Message) { | |
panic("not enough bytes written") | |
} | |
err = conn.Close() | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("success") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment