2017-06-26 168 views
1

我發現用go語言編寫的TCP服務器和TCP客戶端。問題是服務器無法處理多個客戶端,我不知道如何允許它。處理多個網絡客戶端

服務器:

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

誰能幫助我?

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

回答

2

你有幾個問題。首先,您要接受的傳入連接您的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