Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GoでSocket通信プログラム(サーバ側)
package main
import (
"fmt"
"net"
"os"
"time"
)
func main() {
service := ":55555"
tcpAddr, err := net.ResolveTCPAddr("tcp", service)
checkError(err)
listner, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
for {
conn, err := listner.Accept()
if err != nil {
continue
}
go handleClient(conn)
}
}
func handleClient(conn net.Conn) {
defer conn.Close()
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
fmt.Println("client accept!")
messageBuf := make([]byte, 1024)
messageLen, err := conn.Read(messageBuf)
checkError(err)
message := string(messageBuf[:messageLen])
message = message + " too!"
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
conn.Write([]byte(message))
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "fatal: error: %s", err.Error())
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.