使用Go接收和发送TCP客户端

问题描述 投票:1回答:2

我试图在不使用任何库的情况下实现自己的P2P网络。我想构建一个TCP客户端,它从其他节点发送和接收消息。所以所有节点都应该能够通过tcp / ip发送和接收消息。

我目前的问题是,当我启动两个客户端时:一个节点能够接收和发送消息,但另一个节点只发送消息而无法接收消息。

我想我需要以某种方式实现一个频道,但我真的是Go的新手,并且不知道如何实现它。有什么建议?

代码如下:

Main.go:

package main

 func main() {

  address := "127.0.0.1:8081" // IP of the other node; hardcoded for now
  go startServer()
  startClient(address)

} 

helpler.go:

package main

import (
 "bufio"
 "fmt"
 "net"
 "os"
) 

func startClient(address string) {
 //connect to this socket
 connClient, _ := net.Dial("tcp", address)

for {

    //read in input from stdin
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Text to send: ")
    text, _ := reader.ReadString('\n')

    //send to socket
    fmt.Fprint(connClient, text+"\n")

    //listen for reply
    //message, _ := bufio.NewReader(connClient).ReadString('\n')
    //fmt.Print("Message from server: " + message)
  }
 }
func startServer() {
 fmt.Println("Starting...")

//listen on all interfaces
ln, _ := net.Listen("tcp", ":8081")

//accept connection on port
connServer, _ := ln.Accept()

//run loop forever
for {
    //will listen for message to process ending in newline(\n)
    message, _ := bufio.NewReader(connServer).ReadString('\n')

    //fmt.Print("Message Received:" + string(message))

    //sample process for string received
    //newmessage := strings.ToUpper(message)

    connServer.Write([]byte(message + "\n"))
  }
 }
go p2p tcp-ip
2个回答
1
投票

新手Go开发者在这里,但有一个问题,我可以立即考虑。您不能在同一IP和端口中侦听多个进程。

你可能遇到了问题,但是因为你没有检查错误,所以你没有抓住它。如果你有代码检查错误,你可能会注意到你收到这样的错误:

2018/07/11 09:21:06听tcp 127.0.0.1:8081:bind:地址已经

在使用退出状态1

即使不知何故这不是你的问题,进行错误检查仍然是一个好主意。

我建议你添加支票。例如

服务器端

ln, err := net.Listen("tcp", "127.0.0.1:8081")
if err != nil {
    log.Fatal(err)
}

客户端

  conn, err := net.Dial("tcp", "127.0.0.1:8081")
    if err != nil {
        fmt.Println("error:", err)
    }

我想我需要以某种方式实现一个频道

如上所述,我是Go的新手,但我的理解是通道是同一程序中的进程间通信工具。与多个程序无关。如果您在自己喜欢的搜索工具中搜索go频道,可以找到更多信息,但不要相信它是您想要的。


0
投票

尝试使用两个不同的进程作为服务器和客户端。

例如,在主要功能:

func main() {
    connType := os.Getenv("TYPE")

    if connType == "server" {
        startServer()
    } else if connType == "client" {
        startClient()
    } else {
        log.Println("please provide the TYPE arg (TYPE=server or TYPE=client)")
    }
}

然后你可以运行TYPE=server go run yourappTYPE=client go run yourapp。你可以看看这个GitHub repo https://github.com/johannesridho/protobuf-over-tcp

© www.soinside.com 2019 - 2024. All rights reserved.