Golang多个连接到TCP服务器

时间:2016-09-19 14:07:36

标签: go tcp chat

我开发了一个小型GoLang 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))
    }
}

1 个答案:

答案 0 :(得分:0)

你的代码很好。我在Linux上编译,尝试了4个连接。一切都按预期工作。