Created
June 21, 2023 18:24
-
-
Save kehiy/1b784d68060a551b862070ce3571e4cc to your computer and use it in GitHub Desktop.
UDP broadcast server and client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"net" | |
"os" | |
) | |
func main() { | |
// Set up connection to the server | |
conn, err := net.Dial("udp", "localhost:8000") | |
if err != nil { | |
fmt.Println("Error connecting:", err) | |
return | |
} | |
defer conn.Close() | |
// Read input from terminal and send to server | |
scanner := bufio.NewScanner(os.Stdin) | |
go func() { | |
for { | |
buf := make([]byte, 1024) // buffer for incoming message | |
n, err := conn.Read(buf) | |
if err != nil { | |
fmt.Println("Error receiving message:", err) | |
continue | |
} | |
fmt.Printf("Received message: %s\n", string(buf[:n])) | |
} | |
}() | |
for { | |
// send messages to server | |
fmt.Print("Enter message: ") | |
if !scanner.Scan() { | |
break | |
} | |
message := scanner.Text() | |
_, err = conn.Write([]byte(message)) | |
if err != nil { | |
fmt.Println("Error sending message:", err) | |
continue | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net" | |
) | |
func main() { | |
// Set up the server | |
addr := net.UDPAddr{ | |
Port: 8000, | |
IP: net.ParseIP("0.0.0.0"), | |
} | |
conn, err := net.ListenUDP("udp", &addr) | |
if err != nil { | |
fmt.Println("Error listening:", err) | |
return | |
} | |
defer conn.Close() | |
fmt.Println("Server started on port", addr.Port) | |
// Listen for incoming messages | |
buffer := make([]byte, 1024) | |
clients := make(map[string]*net.UDPAddr) | |
for { | |
n, clientAddr, err := conn.ReadFromUDP(buffer) | |
if err != nil { | |
fmt.Println("Error reading:", err) | |
continue | |
} | |
// Add new client | |
if _, ok := clients[clientAddr.String()]; !ok { | |
clients[clientAddr.String()] = clientAddr | |
fmt.Println("New client joined:", clientAddr.String()) | |
} | |
// Broadcast message to all clients | |
message := buffer[:n] | |
for _, addr := range clients { | |
if addr.String() != clientAddr.String() { | |
_, err = conn.WriteToUDP(message, addr) | |
if err != nil { | |
fmt.Println("Error broadcasting message:", err) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment