如何用go创建多个节点
时间: 2024-05-12 07:16:20 浏览: 8
可以使用Go语言的内置包"net"和"bufio"实现多节点连接。具体代码如下:
```
package main
import (
"bufio"
"fmt"
"net"
)
func main() {
nodes := []string{"127.0.0.1:8000", "127.0.0.1:8001", "127.0.0.1:8002"}
for _, node := range nodes {
conn, err := net.Dial("tcp", node)
if err != nil {
fmt.Printf("Failed to connect to %s: %s\n", node, err.Error())
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("Connection closed: %s\n", err.Error())
break
}
fmt.Printf("Received message: %s", message)
}
}
```
本示例代码中,我们将多个节点的地址放在一个字符串数组中,并循环遍历。使用"net.Dial"方法连接每个节点,并在连接成功后使用"go"关键字启动一个新的协程来处理该连接。在"handleConnection"函数中,我们使用"bufio.NewReader"实例化一个读取器,然后不断从该连接中读取数据。当收到的数据为换行符时,我们打印该消息并继续等待下一条消息。