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.
CodePudding user response:
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
CodePudding user response:
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)
}
}