Go Channel Practice V - 祖安萝莉

Go Routine Practice - tcp server&client

violet posted @ Aug 06, 2020 11:35:13 AM in 笔记 with tags Golang GoRoutine , 10562 阅读

 

Server

package main

import (
	"bufio"
	"fmt"
	"net"
	"strings"
	"time"
)

func main() {
	port := ":2333"

	l, err := net.Listen("tcp", port)
	defer l.Close()
	if err != nil {
		panic("fail to listen")
	}

	for i := 0; i < 10; i++ {
		c, err := l.Accept()
		if err != nil {
			fmt.Println("err: ", err.Error())
			return
		}
		go handler(c)
	}
}

func handler(c net.Conn) {
	defer c.Close()
	for {
		netData, err := bufio.NewReader(c).ReadString('\n')
		if err != nil {
			fmt.Println("err: ", err.Error())
			return
		}
		if strings.TrimSpace(string(netData)) == "STOP" {
			fmt.Println("Exit...")
			return
		}
		fmt.Print("-> ", string(netData))
		t := time.Now()
		myTime := t.Format(time.RFC3339) + "\n"
		c.Write([]byte(myTime))
	}
}

Client

package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
)

func main() {
	fmt.Println("vim-go")
	serverHost := "localhost:2333"

	conn, err := net.Dial("tcp", serverHost)
	if err != nil {
		panic("fail to connect to the server")
	}

	for {
		reader := bufio.NewReader(os.Stdin)
		fmt.Printf(">>> ")
		txt, _ := reader.ReadString('\n')
		fmt.Fprintf(conn, txt+"\n")

		message, _ := bufio.NewReader(conn).ReadString('\n')
		fmt.Print("->: " + message)
		if strings.TrimSpace(string(txt)) == "STOP" {
			fmt.Println("TCP client exiting...")
			return
		}
	}
}
Bhawna 说:
Jan 05, 2022 05:16:15 PM

You are posting informative music on this site for us. sex girl whatsapp number


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter