【问题标题】:Handle multiple network clients处理多个网络客户端
【发布时间】:2017-11-29 13:57:27
【问题描述】:

我找到了一个用 Go 语言编写的 TCP Server 和 TCP Client。问题是服务器无法处理多个客户端,我不知道如何允许它。

服务器:

package main

import "net"
import "fmt"
import "bufio"
import "strings" // only needed below for sample processing

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

客户:

package main

import "net"
import "fmt"
import "bufio"
import "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)
  }
}

谁能帮帮我?

来源:https://systembash.com/a-simple-go-tcp-server-and-tcp-client/

【问题讨论】:

    标签: go tcp server client


    【解决方案1】:

    您有几个问题。首先,您要在 for 循环内部接受传入连接。然后,您可能会想要生成一个 goroutine 来处理传入的请求。:

    for {
        // Listen for an incoming connection.
        conn, err := l.Accept()
        if err != nil {
            log.Println("Error accepting: ", err.Error())
            continue
        }
    
        // Handle connections in a new goroutine.
        go myHandler(conn)
    }
    

    资源:
    https://tour.golang.org/concurrency

    GoPlay:
    https://play.golang.org/p/7EovqNWJIx

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      相关资源
      最近更新 更多