-
-
Save night-codes/9a0f2a1933eb06a0feea9f940c09d3d4 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 ( | |
"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) | |
} |
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)) | |
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment