处理多个网络客户端

huangapple go评论89阅读模式
英文:

Handle multiple network clients

问题

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

服务器代码:

package main

import "net"
import "fmt"
import "bufio"
import "strings" // 仅在示例处理中需要

func main() {

  fmt.Println("启动服务器...")

  // 监听所有接口
  ln, _ := net.Listen("tcp", ":8081")

  // 接受连接
  conn, _ := ln.Accept()

  // 永久运行循环(或直到按下Ctrl-C)
  for {
    // 监听以换行符(\n)结尾的消息
    message, _ := bufio.NewReader(conn).ReadString('\n')
    // 输出接收到的消息
    fmt.Print("接收到的消息:", string(message))
    // 对接收到的字符串进行示例处理
    newmessage := strings.ToUpper(message)
    // 将新字符串发送回客户端
    conn.Write([]byte(newmessage + "\n"))
  }
}

客户端代码:

package main

import "net"
import "fmt"
import "bufio"
import "os"

func main() {

  // 连接到该套接字
  conn, _ := net.Dial("tcp", "127.0.0.1:8081")
  for {
    // 从标准输入读取输入
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("要发送的文本:")
    text, _ := reader.ReadString('\n')
    // 发送到套接字
    fmt.Fprintf(conn, text + "\n")
    // 监听回复
    message, _ := bufio.NewReader(conn).ReadString('\n')
    fmt.Print("来自服务器的消息:" + message)
  }
}

有人可以帮助我吗?

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

英文:

I have found a TCP Server and TCP Client written in go language. The problem is that the Server can't handle multiple clients and I don't know how to allow it.

Server:

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

Client:

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

Can anyone help me?

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

答案1

得分: 2

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

for {
    // 监听传入的连接。
    conn, err := l.Accept()
    if err != nil {
        log.Println("错误:", err.Error())
        continue
    }

    // 在一个新的goroutine中处理连接。
    go myHandler(conn)
}

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

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

英文:

You have a couple of issues. First, you want to accept your incoming connections inside your for loop. Then, you're likely going want to spawn off a goroutine to handle the requests coming in.:

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

Resources:
https://tour.golang.org/concurrency

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

huangapple
  • 本文由 发表于 2017年6月27日 00:46:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/44764596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定