与 TCP 服务器的多个连接

问题描述 投票:0回答:1

我开发了一个小型 Go TCP 服务器来制作聊天应用程序。但是,当我尝试将客户端连接到它时,服务器可以与两个客户端一起正常工作,但是每当我尝试连接第三个客户端时,它都不会连接到服务器。我在 Windows 上运行。可能是什么问题?

package main

import (
    "bufio"
    "fmt"
    "net"
)

var allClients map[*Client]int

type Client struct {
    // incoming chan string
    outgoing   chan string
    reader     *bufio.Reader
    writer     *bufio.Writer
    conn       net.Conn
    connection *Client
}

func (client *Client) Read() {
    for {
        line, err := client.reader.ReadString('\n')
        if err == nil {
            if client.connection != nil {
                client.connection.outgoing <- line
            }
            fmt.Println(line)
        } else {
            break
        }

    }

    client.conn.Close()
    delete(allClients, client)
    if client.connection != nil {
        client.connection.connection = nil
    }
    client = nil
}

func (client *Client) Write() {
    for data := range client.outgoing {
        client.writer.WriteString(data)
        client.writer.Flush()
    }
}

func (client *Client) Listen() {
    go client.Read()
    go client.Write()
}

func NewClient(connection net.Conn) *Client {
    writer := bufio.NewWriter(connection)
    reader := bufio.NewReader(connection)

    client := &Client{
        // incoming: make(chan string),
        outgoing: make(chan string),
        conn:     connection,
        reader:   reader,
        writer:   writer,
    }
    client.Listen()

    return client
}

func main() {
    allClients = make(map[*Client]int)
    listener, _ := net.Listen("tcp", ":8080")
    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println(err.Error())
        }
        client := NewClient(conn)
        for clientList, _ := range allClients {
            if clientList.connection == nil {
                client.connection = clientList
                clientList.connection = client
                fmt.Println("Connected")
            }
        }
        allClients[client] = 1
        fmt.Println(len(allClients))
    }
}
go tcp chat
1个回答
0
投票

你的代码没问题。我在 Linux 上编译,尝试使用 4 个连接。一切都按预期进行。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.