-
-
Save ryfjwr/21e01fb5e133861b41e981e14ced8672 to your computer and use it in GitHub Desktop.
simple tcp client and server
This file contains 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" | |
"syscall" | |
"time" | |
) | |
func main() { | |
// imported | |
// http://www.geekpage.jp/programming/linux-network/tcp-1.php | |
server := syscall.SockaddrInet4{Port: 12345} | |
sock, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0) | |
if err != nil { | |
fmt.Println("sock init error") | |
fmt.Println(err.Error()) | |
} | |
copy(server.Addr[:], net.ParseIP("0.0.0.0").To4()) | |
err = syscall.Connect(sock, &server) | |
if err != nil { | |
fmt.Println("sock connect Error") | |
fmt.Println(err.Error()) | |
} | |
var buf []byte | |
_, err = syscall.Read(sock, buf) | |
if err != nil { | |
fmt.Println("Read Error") | |
fmt.Println(err.Error()) | |
} | |
fmt.Println(buf) | |
time.Sleep(2 * time.Second) | |
syscall.Close(sock) | |
} |
This file contains 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" | |
"syscall" | |
) | |
// http://www.geekpage.jp/programming/linux-network/tcp-1.php | |
func main() { | |
addr := syscall.SockaddrInet4{Port: 12345} | |
sock, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0) | |
if err != nil { | |
fmt.Println("sock init error") | |
} | |
// https://gist.github.com/tevino/3a4f4ec4ea9d0ca66d4f | |
copy(addr.Addr[:], net.ParseIP("0.0.0.0").To4()) | |
syscall.Bind(sock, &addr) | |
err = syscall.Listen(sock, 5) | |
if err != nil { | |
fmt.Println("listen Error") | |
fmt.Println(err.Error()) | |
} | |
sock1, _, err := syscall.Accept(sock) | |
if err != nil { | |
fmt.Println("error occured") | |
} | |
_str := "HELLO" | |
str := []byte(_str) | |
fmt.Println("byte order") | |
fmt.Println(str) | |
ret, err := syscall.Write(sock, str) | |
if err != nil { | |
fmt.Println("Write Error") | |
fmt.Println(ret) | |
fmt.Println(err.Error()) | |
} | |
fmt.Println("exit") | |
syscall.Close(sock) | |
syscall.Close(sock1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment