duanjingwei7239 2016-03-30 21:26
浏览 22

在写一个之前接受一条信息

I have a server that listens to 2 ports and transfers messages between the 2 ports. The only problem is that each client (or each port) has to submit a message before they can receive the previous message that the other port sent. For example, if client 1 says "hello", client 2 will not receive the message unless he sends a message first.

I want to find a way to make it so that each client will have to receive the previous message before being able to send a new one. (Since Client 1 will not have anything to receive until Client 2 says something, I am planning to send it a string that has placeholder text.)

Can anyone help me with how to go about this? I try putting my listening code and my code for writing a message for each client into their own go routines, but that did not do the job. Any help will be appreciated.

Here is my code:

Server

package main

import (
    "fmt"
    "log"
    "net"
)

var message string = "Client 2 is receiving your message"

func main() {
    fmt.Println("The server is listening on Port 3000 and 8080")
    //Set up listeners for the ports each client is using
    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)
    }
}

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([]byte(message))
                if err != nil {
                        log.Fatalln(err)
                }
                fmt.Print("Message sent: ", string(data))
                message = string(data)
        }
}

Client 1

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

        _, 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
        }

    }
}

My second client is the same as my first except "localhost:3000" is replaced with "localhost:8080".

I will appreciate any help! I'm fairly new to networking and Go, so any tips will be great.

  • 写回答

1条回答 默认 最新

  • duanji1899 2016-03-30 21:49
    关注

    Right now your Server is just an echo. It responds with the message received from the client.

    If you want to relay the message between two clients, the first thing you need to figure out is what should happen if 3 clients connect (2 to the first port, 1 to the other)?

    If you expect to have just one client connected to each port you could do something like this (pseudo-go-code):

    func main() {
      // ...
      # Channels must be buffered or else clients will deadlock.
      relay := make(chan string, 1)
      go acceptLoop(listener1, relay)
      acceptLoop(listener2, relay)
    }
    
    func acceptLoop(l, relay) {
      for {
        conn := l.Accept()
        for {
           relay <- conn.Read()
           conn.Write(<-relay)
        }
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog