golang简易版TCP client server

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



<img src="https://www.361way.com/wp-content/uploads/2018/12/simple-tcp-client-server.png" width="374" height="201" title="simple-tcp-client-server" alt="simple-tcp-client-server" />



<strong>server端代码如下</strong>:



<br />
package main
import "net"
import "fmt"
import "bufio"
import "strings"
func main() {
    fmt.Println("Launching server...")
    // listen on all interfaces
    ln, _ := net.Listen("tcp", ":8081")
    // accept connection on port
    conn, _ := ln.Accept()
    // run loop forever (or until ctrl-c)
    for {
        // will listen for message to process ending in newline (\n)
        message, _ := bufio.NewReader(conn).ReadString('\n')
        // output message received
        fmt.Print("Message Received:", string(message))
        // sample process for string received
        newmessage := strings.ToUpper(message)
        // send new string back to client
        conn.Write([]byte(newmessage + "\n"))
    }
}
<br />



<strong>client端代码如下</strong>:



<br />
package main
import (
    "bufio"
    "fmt"
    "net"
    "os"
)
func main() {
    // connect to this socket
    conn, _ := net.Dial("tcp", "127.0.0.1:8081")
    for {
        // read in input from stdin
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Text to send: ")
        text, _ := reader.ReadString('\n')
        // send to socket
        fmt.Fprintf(conn, text+"\n")
        // listen for reply
        message, _ := bufio.NewReader(conn).ReadString('\n')
        fmt.Print("Message from server: " + message)
    }
}
<br />

golang简易版TCP client server》有1条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注