go - Go Routines 及其并发问题

标签 go broker

TL;DR 接受并连接两个独立的 SETS 连接。想用 RPC 并发完成。

我正在尝试在我的计算机上创建半分布式系统。我现在正在处理的这段代码有点像代理节点,换句话说,它总是从一个端口接受客户端连接。它还不断地接受来自不同端口的后端节点连接。 我正在尝试找到一种方法来同时倾听两者并为两者提供服务。我正在使用 RPC,我尝试这样做的方式是这样的: 主要:

func main(){  
 ...  
 rpc.Register(myInterface)  
 l, err := net.Listen("tcp", client_port)  
 if err != nil {...}  
 go handleClients(l)  
 node_l, err := net.Listen("tcp", node_port)  
 if err != nil{...}   
 go setUpIncomingNodes(node_l, chan)  
 for{// add nodes to a list from chan} 
}

并发函数:

// Adds clients to be connected
func handleClients(listener net.Listener){
 for{
  conn, err :=listener.Accept()
  if err != nil{...}
  // Starts up a blocking (on that thread) RPC connection
  go rpc.serveConn(conn)
 }
}
func setUpIncomingNodes(node_listener net.Listener, incoming_nodes chan<- net.Conn){
 for{
  conn, err := node_listener.Accept()
  if err != nil{...}
  incoming_nodes <- conn     
 }
}

问题是它不服务第一个节点,直到第二个节点出现。我不明白为什么。此外,似乎一次只能发生一个连接,但我认为 RPC 服务于不同的端口(因此不会阻止它)。非常感谢任何帮助。

我尝试关注 this tutorial但是我发现情况太不一样了,它也使用了不同版本的 Go。我使用两种类型的节点/连接,其中类型 A 需要通过代理提供给类型 B。

最佳答案

最后,我认为问题在于我试图将监听器传递Go routine,因此每个 go routine 都依赖于 main线。工作解决方案最终变得如此简单:

func main(){
 ...
 node_ip_port := "127.0.0.1:9000"
 client_ip_port := "127.0.0.1:1000"
 nodeChan := make(chan net.Conn, 20)

 go func(ip_port string, nodeChan chan<- net.Conn) {
    l, err := net.Listen("tcp", node_ip)
    if err != nil {
        log.Fatal("Had an error connecting to node", err)
    }
    for {
        conn, _ := l.Accept()
        kvChan <- conn
    }
  }(node_ip_port, nodeChan)

 go func(ip_port string) {
    l, err := net.Listen("tcp", ip_port)
    if err != nil {
        log.Fatal("Had an error connecting to client", err)
    }
    for {
        conn, _ := l.Accept()
        go rpc.ServeConn(conn)
    }
  }(client_ip_port)
  // List of connected nodes
  nodeList := list.New()
  for {
    node := <-nodeChan
    nodeList.PushBack(node)
    // My RPC functions use the nodes in this list to serve :-)
  }
 }

关于go - Go Routines 及其并发问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28686018/

相关文章:

go - 如何防止 http 客户端进行 TLS 重新协商?

json - 使用 Golang go-simplejson 遍历 Json

azure - MQTT 代理到外界

java - 使用 WebSphere Message Broker (WMB) 将 CSV 文件转换为 Java 对象

Tridion 2009 SP1 : Image Thumbnails - How to publish the original image as well?

html - 如何使用 jquery 从 Rotten Tomatoes 检索搜索列表?

github - 困惑 : GitHub Project broken(? ), 指令不明确 : Mercurial setup(? )

mysql - 无法使用来自 Google App Engine 的 SSL + Golang 连接到 Google Cloud SQL

java - 盈透证券 API 和 Web 应用程序

visual-c++ - 客户端/服务器通信中的中间件