golang java 服务器,Golang多个连接到TCP服务器

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

}

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值