Skip to content

Instantly share code, notes, and snippets.

@kenshinx
Last active February 3, 2024 18:49
Show Gist options
  • Save kenshinx/5796276 to your computer and use it in GitHub Desktop.
Save kenshinx/5796276 to your computer and use it in GitHub Desktop.
golang socket server & client ping-pong demo
package main
import (
"os"
"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)
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
defer conn.Close()
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))
if err != nil {
log.Fatalf("Socket listen port %d failed,%s", port, err)
os.Exit(1)
}
defer listen.Close()
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
Copy link

What's does ILOOP mean in the code?

@vipulsodha
Copy link

vipulsodha 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
Copy link

How to detect closed TCP connection when client disconnected?

@you06
Copy link

you06 commented Aug 29, 2019

Thanks for your gist! I think the defer listen.Close() action should be after err handle.

@kenshinx
Copy link
Author

Revised, thanks a lot @you06

@chzgustavo
Copy link

Thank you very much, your contribution helped me !

@skpywatts
Copy link

Verify Github on Galaxy. gid:853fCjKgvQfoCSEgaWbQeg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment