golang简易版TCP client server
每个编程语言都会有socket类的编程,最常用的就是tcp c/s 和udp c/s,这里就使用golang实现一个简单的tcp server client程序,server会等待 client发送数据给他,server接收到数据后,再处理后回传给client 。具体效果如下图:
server端代码如下:
1package main
2import "net"
3import "fmt"
4import "bufio"
5import "strings"
6func main() {
7 fmt.Println("Launching server...")
8 // listen on all interfaces
9 ln, _ := net.Listen("tcp", ":8081")
10 // accept connection on port
11 conn, _ := ln.Accept()
12 // run loop forever (or until ctrl-c)
13 for {
14 // will listen for message to process ending in newline (\n)
15 message, _ := bufio.NewReader(conn).ReadString('\n')
16 // output message received
17 fmt.Print("Message Received:", string(message))
18 // sample process for string received
19 newmessage := strings.ToUpper(message)
20 // send new string back to client
21 conn.Write([]byte(newmessage + "\n"))
22 }
23}
client端代码如下:
1package main
2import (
3 "bufio"
4 "fmt"
5 "net"
6 "os"
7)
8func main() {
9 // connect to this socket
10 conn, _ := net.Dial("tcp", "127.0.0.1:8081")
11 for {
12 // read in input from stdin
13 reader := bufio.NewReader(os.Stdin)
14 fmt.Print("Text to send: ")
15 text, _ := reader.ReadString('\n')
16 // send to socket
17 fmt.Fprintf(conn, text+"\n")
18 // listen for reply
19 message, _ := bufio.NewReader(conn).ReadString('\n')
20 fmt.Print("Message from server: " + message)
21 }
22}
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/go-simple-tcp-client-server/5932.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.