golang简易版TCP client server

2018年12月12日 发表评论 阅读评论

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

simple-tcp-client-server

server端代码如下

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"))
	}
}

client端代码如下

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)
	}
}




本站的发展离不开您的资助,金额随意,欢迎来赏!

You can donate through PayPal.
My paypal id: itybku@139.com
Paypal page: https://www.paypal.me/361way