Last active
February 3, 2024 18:49
-
-
Save kenshinx/5796276 to your computer and use it in GitHub Desktop.
golang socket server & client ping-pong demo
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 ( | |
"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) | |
} |
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 ( | |
"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) | |
} |
Thank you very much, your contribution helped me !
Verify Github on Galaxy. gid:853fCjKgvQfoCSEgaWbQeg
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Revised, thanks a lot @you06