douzhang8144 2017-06-26 16:46
浏览 60
已采纳

处理多个网络客户端

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

Can anyone help me?

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

  • 写回答

1条回答 默认 最新

  • dtch60248 2017-06-26 16:49
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效