每个编程语言都会有socket类的编程,最常用的就是tcp c/s 和udp c/s,这里就使用golang实现一个简单的tcp server client程序,server会等待 client发送数据给他,server接收到数据后,再处理后回传给client 。具体效果如下图:

simple-tcp-client-server
simple-tcp-client-server

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}