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))
}
}
세 번째 클라이언트를 연결할 때 오류가 발생합니까? 그 오류가 무엇입니까? – AJPennster
지도를 동시에 사용할 수 없습니다. 경주 감지기로 코드를 확인하십시오. – JimB
@AJPennster 내가 받고있다 GetFileAttributesEx client.go : 지정한 파일을 찾을 수 없습니다. 서버 쪽에서 클라이언트 쪽에서 오류가 발생했습니다. 나는 창문에서 달리고있다. – shubham003