从一个端口发送消息到另一个端口

huangapple go评论89阅读模式
英文:

Sending a message from one port to another

问题

我有一个服务器和两个客户端,每个客户端使用自己的端口。当客户端向服务器发送消息时,服务器会将消息回显给发送者。然后,服务器应该将消息发送给另一个客户端。这就是我遇到问题的地方。

我认为在writeMessage()函数中可能设置连接有问题,但我不太确定。目前,为了调试目的,我只让该函数尝试向端口8080的客户端2写入。

服务器代码如下:

package main

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

var message string = ""

func main() {
    fmt.Println("The server is listening on Port 3000 and 8080")
    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)
}

func acceptLoop(l net.Listener) {
    defer l.Close()
    for {
        c, err := l.Accept()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("New connection found!")
		listenConnection(c)
    }
}

func listenConnection(conn net.Conn) {
    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(string(data))
		conn.Write(data)
		message = string(data)
		writeMessage()
    }
}

func writeMessage(){
	conn2, e := net.Dial("tcp", "localhost:8080")
	if e != nil {
        log.Fatalln(e)
    }
	defer conn2.Close()
	conn2.Write([]byte(message))
}

客户端1代码如下:

package main
 
import (
    "fmt"
    "log"
    "net"
	"bufio"
	"os"
)
 
func main() {
    conn, err := net.Dial("tcp", "localhost:3000")
    if err != nil {
        log.Fatalln(err)
    }

	go listenConnection(conn, err)
	writeMessage(conn, err)
}

func listenConnection(conn net.Conn, err error){
    for {
        buffer := make([]byte, 1400)
        dataSize, err := conn.Read(buffer)
        if err != nil {
            fmt.Println("connection closed")
            return
        }

        data := buffer[:dataSize]
        fmt.Print("Server: ", string(data))
    }
}

func writeMessage(conn net.Conn, err error){
    for {
 		reader := bufio.NewReader(os.Stdin)
		text, _ := reader.ReadString('\n')
		text = "3000: " + text

        _, err = conn.Write([]byte(text))
        if err != nil {
            log.Fatalln(err)
        }
    }
}

(我的第二个客户端与第一个客户端相同,只是将端口3000替换为8080。)

为了复现问题,用户需要运行服务器代码,然后运行两个客户端。然后客户端可以向服务器发送消息。

希望能得到帮助。我完全搞不清楚这个问题。希望一些有经验的Go用户能够提供帮助!

英文:

I have a server and 2 clients each using their own port. When a client sends a message to the server, the server echoes it back to the sender. Then, the server is supposed to send the message to the other client as well. This is where I'm having issues.

I believe I may be setting up the connection wrong in writeMessage(), but I am not entirely sure. At the moment, I have the function just trying to write to client 2 on port 8080 for debugging purposes.

Server:

package main
import (
"fmt"
"log"
"net"
)
var message string = ""
func main() {
fmt.Println("The server is listening on Port 3000 and 8080")
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)
}
func acceptLoop(l net.Listener) {
defer l.Close()
for {
c, err := l.Accept()
if err != nil {
log.Fatal(err)
}
fmt.Println("New connection found!")
listenConnection(c)
}
}
func listenConnection(conn net.Conn) {
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(string(data))
conn.Write(data)
message = string(data)
writeMessage()
}
}
func writeMessage(){
conn2, e := net.Dial("tcp", "localhost:8080")
if e != nil {
log.Fatalln(e)
}
defer conn2.Close()
conn2.Write([]byte(message))
}

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)
}
go listenConnection(conn, err)
writeMessage(conn, err)
}
func listenConnection(conn net.Conn, err error){
for {
buffer := make([]byte, 1400)
dataSize, err := conn.Read(buffer)
if err != nil {
fmt.Println("connection closed")
return
}
data := buffer[:dataSize]
fmt.Print("Server: ", string(data))
}
}
func writeMessage(conn net.Conn, err error){
for {
reader := bufio.NewReader(os.Stdin)
//fmt.Print("Enter message: ")
text, _ := reader.ReadString('\n')
text = "3000: " + text
_, err = conn.Write([]byte(text))
if err != nil {
log.Fatalln(err)
}
}
}

(My second client is the same as my first except port 3000 is replaced with 8080.)

In order to replicate the problem, the user has to run the server code and then both of the clients. The clients can then send messages to the server.

Any help with this would be greatly appreciated. I cannot figure this out at all. Hopefully some more experienced Go users will be able to help!

答案1

得分: 0

你的逻辑似乎有缺陷,acceptloop调用了listenconnection,这样就在一个无限循环内创建了另一个无限循环。我认为你需要使用用例场景重新构建系统。

如果我理解正确,你想要一个服务器等待客户端连接。首先,客户端1连接并发送一些数据。服务器接受这个连接,每个客户端只需要接受一次。此时,如果客户端2在线,将数据发送给客户端2。所有这些都在一个无限循环中发生。

请查看这段代码:
https://play.golang.org/p/_5AREG3jnG

英文:

your logic seems to have flaws, where acceptloop calls for listenconnection, it creates an infinite loop inside an infinite loop. I think you need to reconstruct the system with use cases and scenarios.

If my understanding is right, you like to have a server waiting for clients to connect. First, client1 comes in, sends some data. The server accepts this connection, and it only needs to accept once for each client. At this point, if the client2 is online, send data to client2. All of this happens in an infinite loop.

Checkout this code
https://play.golang.org/p/_5AREG3jnG

huangapple
  • 本文由 发表于 2016年4月18日 09:05:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/36683960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定