2016-09-19 35 views
1

我开发了一个小型GoLang TCP服务器来创建一个聊天应用程序。但是当我尝试将客户端连接到它时,服务器对两个客户端正常工作,但每当我尝试连接第三个客户端时,它都没有连接到服务器。我在窗户上跑步。有谁可以帮助我解决这个问题?Golang与TCP服务器的多个连接

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

连接第三个客户端时出现错误?那是什么错误? – AJPennster

+2

您不能同时使用地图。用比赛检测器检查你的代码。 – JimB

+0

@AJPennster我得到 GetFileAttributesEx client.go:系统找不到指定的文件。服务器端的客户端错误我没有看到任何东西。我在窗户上跑步。 – shubham003

回答

0

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

+0

所以它可能是操作系统特定的问题。我会尝试在Linux上。谢谢 – shubham003