问题描述
我试图修改回显服务器程序以创建聊天客户端.当前,启动客户端时,我的服务器正在侦听端口.然后,客户端可以键入并向服务器发送消息,服务器将回显该消息.
I am trying to modify my echo server program in order to create a chat client. Currently, I have my server listening to a port when I start up my client. Then, the client can type and send a message to the server and the server will echo it back.
但是,我希望能够将2个客户端连接到2个不同的端口,并让客户端通过服务器相互发送消息.有什么办法可以做到吗?我假设第一步将是侦听2个端口而不是一个.
However, I would like to be able to connect 2 clients to 2 different ports and let the clients send messages to each other over the server. Is there any way I could do this? I am assuming that the first step would be to listen to 2 ports instead of one.
这是我到目前为止所拥有的.
Here is what I have so far.
服务器:
package main
import (
"fmt"
"log"
"net"
)
func main() {
fmt.Println("The server is listening on Port 3000")
listener, _ := net.Listen("tcp", "localhost:3000")
//listener2, _ := net.Listen("tcp", "localhost:8080")
defer listener.Close()
//defer listener2.Close()
// Listen for connections
for {
conn, _ := listener.Accept()
//conn2, _ := listener2.Accept()
fmt.Println("New connection found!")
go listenConnection(conn)
//go listenConnection(conn2)
}
}
//Listen for messages and reply
func listenConnection(conn net.Conn) {
fmt.Println("Yay")
for {
buffer := make([]byte, 1400)
dataSize, err := conn.Read(buffer)
if err != nil {
fmt.Println("Connection has closed")
return
}
//This is the message you received
data := buffer[:dataSize]
fmt.Print("Received message: ", string(data))
// Send the message back
_, err = conn.Write(data)
if err != nil {
log.Fatalln(err)
}
fmt.Print("Message sent: ", string(data))
}
}
客户:
package main
import (
"fmt"
"log"
"net"
"bufio"
"os"
)
func main() {
conn, err := net.Dial("tcp", "localhost:3000")
if err != nil {
log.Fatalln(err)
}
for {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
_, err = conn.Write([]byte(text))
if err != nil {
log.Fatalln(err)
}
for {
buffer := make([]byte, 1400)
dataSize, err := conn.Read(buffer)
if err != nil {
fmt.Println("The connection has closed!")
return
}
data := buffer[:dataSize]
fmt.Println("Received message: ", string(data))
break
}
}
}
有没有办法在1台服务器上侦听2个客户端(端口)并使它们进行通信?是否可以使用同一端口上的两个客户端执行此操作?我尝试在Server程序中添加另一个侦听器,但由于它们无法正常工作,因此暂时将其注释掉.我将不胜感激!
Is there any way to listen to 2 clients (ports) on 1 server and let them communicate? Is it possible to do this with both clients on the same port? I tried adding another listener in the Server program, but I commented those lines out for now as they did not work. I will appreciate any help!
推荐答案
问题中的服务器代码可在同一端口上处理多个客户端.
The server code in the question handles multiple clients on the same port.
要使用两个端口,请创建两个侦听器,并在单独的goroutine中为这些侦听器运行accept循环:
To work with two ports, create two listeners and run the accept loops for these listeners in separate goroutines:
func main() {
fmt.Println("The server is listening on Port 3000")
listener, err := net.Listen("tcp", "localhost:3000")
if err != nil {
log.Fatal(err)
}
listener2, err := net.Listen("tcp", "localhost:8080")
if err != nil {
log.Fatal(err)
}
go acceptLoop(listener)
acceptLoop(listener2) // run in the main goroutine
}
func acceptLoop(l net.Listener) {
defer l.Close()
for {
c, err := l.Accept()
if err != nil {
log.Fatal(err)
}
fmt.Println("New connection found!")
go listenConnection(c)
}
}
此外,请不要忽略错误.此答案中的代码通过调用log.Fatal处理错误.这可能适合您的应用程序,也可能不合适.
Also, don't ignore errors. The code in this answer handles errors by calling log.Fatal. That may or may not be appropriate for your application.
这篇关于侦听1个服务器上的2个端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!