堕落不振功业废,勤耕不辍日月新

golang简易版TCP client server

Python hailen 19℃

每个编程语言都会有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 (
)
		message, _ := bufio.NewReader(conn).ReadString('
')
		// 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 + "
"))
	}
}

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('
')
		// send to socket
		fmt.Fprintf(conn, text+"
")
		// listen for reply
		message, _ := bufio.NewReader(conn).ReadString('
')
		fmt.Print("Message from server: " + message)
	}
}

golang简易版TCP client server,首发于运维之路

转载请注明:我是IT » golang简易版TCP client server

喜欢 (0)or分享 (0)