简体   繁体   中英

Listen to 2 Ports on 1 Server

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.

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.

Server:

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

Client:

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
        }

    }
}

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM