Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
golang socket server & client ping-pong demo
package main
import (
"log"
"net"
"strconv"
"strings"
)
const (
message = "Ping"
StopCharacter = "\r\n\r\n"
)
func SocketClient(ip string, port int) {
addr := strings.Join([]string{ip, strconv.Itoa(port)}, ":")
conn, err := net.Dial("tcp", addr)
defer conn.Close()
if err != nil {
log.Fatalln(err)
}
conn.Write([]byte(message))
conn.Write([]byte(StopCharacter))
log.Printf("Send: %s", message)
buff := make([]byte, 1024)
n, _ := conn.Read(buff)
log.Printf("Receive: %s", buff[:n])
}
func main() {
var (
ip = "127.0.0.1"
port = 3333
)
SocketClient(ip, port)
}
package main
import (
"bufio"
"io"
"log"
"net"
"os"
"strconv"
"strings"
)
const (
Message = "Pong"
StopCharacter = "\r\n\r\n"
)
func SocketServer(port int) {
listen, err := net.Listen("tcp4", ":"+strconv.Itoa(port))
defer listen.Close()
if err != nil {
log.Fatalf("Socket listen port %d failed,%s", port, err)
os.Exit(1)
}
log.Printf("Begin listen port: %d", port)
for {
conn, err := listen.Accept()
if err != nil {
log.Fatalln(err)
continue
}
go handler(conn)
}
}
func handler(conn net.Conn) {
defer conn.Close()
var (
buf = make([]byte, 1024)
r = bufio.NewReader(conn)
w = bufio.NewWriter(conn)
)
ILOOP:
for {
n, err := r.Read(buf)
data := string(buf[:n])
switch err {
case io.EOF:
break ILOOP
case nil:
log.Println("Receive:", data)
if isTransportOver(data) {
break ILOOP
}
default:
log.Fatalf("Receive data failed:%s", err)
return
}
}
w.Write([]byte(Message))
w.Flush()
log.Printf("Send: %s", Message)
}
func isTransportOver(data string) (over bool) {
over = strings.HasSuffix(data, "\r\n\r\n")
return
}
func main() {
port := 3333
SocketServer(port)
}
@cre8andctrl

This comment has been minimized.

Copy link

commented Jun 19, 2018

What's does ILOOP mean in the code?

@vipulsodha

This comment has been minimized.

Copy link

commented Jun 23, 2018

@cre8andctrl it breaks the outer for Loop, since writing only break; will only break the switch statement execution and not the the outer for loop

@thuongtin

This comment has been minimized.

Copy link

commented May 31, 2019

How to detect closed TCP connection when client disconnected?

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.