加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang多个连接到TCP服务器

发布时间:2020-12-16 09:23:08 所属栏目:大数据 来源:网络整理
导读:我开发了一个小型GoLang TCP服务器来制作聊天应用程序.但是当我尝试将客户端连接到它时,服务器可以正常使用两个客户端,但每当我尝试连接第三个客户端时,它都没有连接到服务器.我在 Windows上运行.可能有什么问题可以帮助我吗? package mainimport ( "bufio"
我开发了一个小型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))
    }
}

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读