How to communication between 2 program with different IP in Golang

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

How to communication between 2 program with different IP in Golang

问题

有人可以推荐一个通信协议,可以连接两个具有不同 IP 地址(其他设备)的 Golang 程序吗?因为当我尝试在 Golang 中进行 Socket 编程时,它只能连接本地主机上的程序。

英文:

can someone recommend me a communication protocol that can connect 2 Golang programs with different IP address (other devices) ? Because when I try Socket programming in Golang, it can only connect programs on localhost.

答案1

得分: 1

如果你想在家庭网络上运行一个服务器,并且希望能够从家庭网络外部连接到它,首先:
你需要将服务器套接字绑定到你的本地IP地址,可能是类似于192.168...的地址,并监听它。
其次:
当来自网络外部的系统发送数据包到你的服务器时,它们发送到你的公共IP地址,你可以通过搜索“what is my ip”来找到它,因此你的路由器不知道应该将数据包转发到哪个本地IP地址,这就是为什么你需要进行端口转发的原因,它基本上告诉路由器:“嘿,每当你收到一个在端口'n'上的数据包时,将其发送到IP地址为'x.x.x.x'的系统上”。

所以,如果你的本地IP是192.168.1.10,公共IP是5.68.125.48,并且你正在监听8080端口,在你的路由器设置页面上,你需要将端口8080转发到192.168.1.10,然后在客户端上,你连接并发送数据包到5.68.125.48:8080,现在路由器知道在本地网络上应该接收该数据包的是谁。

英文:

if you want to run a server on your home network which is probably behind a NAT and connect to it from outside of you home network
first:
you need to bind your server socket to your local ip address which might be something
like 192.168.... and listen to it
second:
when systems outside of your network send packets to your server they send it to your
public Ip which you can find by googling "what is my ip" and therefore your router
has no idea what local ip address it should forward the packet to that is why you
need to do Port Forwarding which basically tells the router "hey when ever you
received a packet on port "n" send it to a system with the ip address of "x.x.x.x".

so if you local ip is 192.168.1.10 and your public ip is 5.68.125.48 and you are listening on port 8080 on your router setup page you forward port 8080 to 192.168.1.10 and on the client side you connect and send packets to 5.68.125.48:8080 now the router knows who on the local network should receive the packet

答案2

得分: 1

你可以尝试这样的解决方案:

package main

import (
	"bufio"
	"fmt"
	"net"
	"strconv"
	"time"
)

func main() {
	fmt.Println("服务器已启动...")
	ln, err := net.Listen("tcp", ":8000")
	if err != nil {
		fmt.Println("启动套接字服务器时出错:" + err.Error())
	}
	for {
		conn, err := ln.Accept()
		if err != nil {
			fmt.Println("监听客户端时出错:" + err.Error())
			continue
		}
		fmt.Println(conn.RemoteAddr().String() + ": 客户端已连接")
		go receiveData(conn)
		go sendData(conn)
	}
}

func sendData(conn net.Conn) {
	i := 0
	for {
		_, err := fmt.Fprintf(conn, strconv.Itoa(i)+". 来自服务器的数据\n")
		i++
		if err != nil {
			fmt.Println(conn.RemoteAddr().String() + ": 结束发送数据")
			return
		}
		time.Sleep(time.Duration(1) * time.Second)
	}
}

func receiveData(conn net.Conn) {
	for {
		message, err := bufio.NewReader(conn).ReadString('\n')
		if err != nil {
			fmt.Println(conn.RemoteAddr().String() + ": 客户端已断开连接")
			conn.Close()
			fmt.Println(conn.RemoteAddr().String() + ": 结束接收数据")
			return
		}
		fmt.Print(conn.RemoteAddr().String() + ": 收到 " + message)
	}
}

这是一个简单的TCP服务器示例,它会接收客户端的连接并发送数据给客户端。sendData函数会不断发送递增的数据给客户端,而receiveData函数会接收客户端发送的数据并打印出来。你可以根据自己的需求进行修改和扩展。

英文:

You can try a solution like this:

package main
import (
"bufio"
"fmt"
"net"
"strconv"
"time"
)
func main() {
fmt.Println("Server started...")
ln, err := net.Listen("tcp", ":8000")
if err != nil {
fmt.Println("Error starting socket server: " + err.Error())
}
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println("Error listening to client: " + err.Error())
continue
}
fmt.Println(conn.RemoteAddr().String() + ": client connected")
go receiveData(conn)
go sendData(conn)
}
}
func sendData(conn net.Conn) {
i := 0
for {
_, err := fmt.Fprintf(conn, strconv.Itoa(i)+". data from server\n")
i++
if err != nil {
fmt.Println(conn.RemoteAddr().String() + ": end sending data")
return
}
time.Sleep(time.Duration(1) * time.Second)
}
}
func receiveData(conn net.Conn) {
for {
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
fmt.Println(conn.RemoteAddr().String() + ": client disconnected")
conn.Close()
fmt.Println(conn.RemoteAddr().String() + ": end receiving data")
return
}
fmt.Print(conn.RemoteAddr().String() + ": received " + message)
}
}

huangapple
  • 本文由 发表于 2022年8月1日 16:25:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/73190830.html
匿名

发表评论

匿名网友

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

确定