As I'm finding quite some examples how to write a go server and client, this works locally on one machine.
Now I'm trying to communicate in my local network between two PCs, one running the go server script, one the client.
However, I can't establish a connection because of the error:
Error: listen udp 192.168.11.6:10001: bind: cannot assign requested address
panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x0 pc=0x401376] // ...
Of course I will post my code (client, where the problem occurs):
package main
import (
"fmt"
"net"
"strconv"
"time"
)
func CheckError(err error) {
if err != nil {
fmt.Println("Error: ", err)
}
}
func main() {
ServerAddr, err := net.ResolveUDPAddr("udp", "192.168.11.6:10001")
CheckError(err)
Conn, err := net.ListenUDP("udp", ServerAddr)
CheckError(err)
defer Conn.Close()
i := 0
for {
msg := strconv.Itoa(i)
i++
buf := []byte(msg)
_, err = Conn.WriteToUDP(buf, ServerAddr)
time.Sleep(time.Second * 1)
}
}
Server:
package main
import (
"fmt"
"net"
"os"
)
/* A Simple function to verify error */
func CheckError(err error) {
if err != nil {
fmt.Println("Error: " , err)
os.Exit(0)
}
}
func main() {
ServerAddr,err := net.ResolveUDPAddr("udp",":10001")
CheckError(err)
ServerConn, err := net.ListenUDP("udp", ServerAddr)
CheckError(err)
defer ServerConn.Close()
buf := make([]byte, 1024)
for {
fmt.Println("Starting...")
n,addr,err := ServerConn.ReadFromUDP(buf)
fmt.Println("Received ",string(buf[0:n]), " from ",addr)
ServerConn.WriteToUDP([]byte("hello there!"), addr)
if err != nil {
fmt.Println("Error: ",err)
}
}
}
The client has the local network IP address 192.168.11.8 and the server 192.168.11.6. They can also ping each other, and I'm opening the port when Windows asks for it.
I'm happy about all suggestions. I struggle with this because I only find localhost server client go examples.