108afec172
All checks were successful
catsync-build / simple-build (amd64, linux, 1.23.1) (push) Successful in 38s
catsync-build / simple-build (amd64, linux, oldstable) (push) Successful in 38s
catsync-build / simple-build (amd64, windows, 1.23.1) (push) Successful in 35s
catsync-build / simple-build (amd64, windows, oldstable) (push) Successful in 35s
catsync-build / simple-build (arm64, linux, 1.23.1) (push) Successful in 38s
catsync-build / simple-build (arm64, linux, oldstable) (push) Successful in 37s
97 lines
2.0 KiB
Go
97 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"code.uocat.com/tqcq/catsync/pb"
|
|
"context"
|
|
"fmt"
|
|
"google.golang.org/protobuf/proto"
|
|
"google.golang.org/protobuf/types/known/timestamppb"
|
|
"net"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
PeerList = make(map[string]net.UDPAddr)
|
|
)
|
|
|
|
func LANServer(ctx context.Context, conn *net.UDPConn) {
|
|
|
|
var wait_group sync.WaitGroup
|
|
defer wait_group.Wait()
|
|
for {
|
|
buf := make([]byte, 1024)
|
|
n, remote_addr, err := conn.ReadFromUDP(buf)
|
|
if err != nil {
|
|
fmt.Printf("Recv failed. %v\n", err)
|
|
continue
|
|
}
|
|
if n != 0 {
|
|
// process request
|
|
wait_group.Add(1)
|
|
go func() {
|
|
defer wait_group.Done()
|
|
|
|
fmt.Printf("remote_addr: %s\n", remote_addr.AddrPort().String())
|
|
pm := &pb.PeerMessage{}
|
|
err := proto.Unmarshal(buf[:n], pm)
|
|
if err != nil {
|
|
fmt.Printf("Unmarshal failed. %v\n", err)
|
|
return
|
|
}
|
|
|
|
fmt.Printf("uid: %s, send_timestamp: %s\n", pm.Uid, pm.SendTimestamp.AsTime().Local())
|
|
}()
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
func LANClient(ctx context.Context, conn *net.UDPConn) {
|
|
broadcast_addr, err := net.ResolveUDPAddr("udp4", "255.255.255.255:8829")
|
|
if err != nil {
|
|
fmt.Printf("err: %v", err)
|
|
return
|
|
}
|
|
|
|
for {
|
|
pm := &pb.PeerMessage{
|
|
MagicNumber: 13,
|
|
Version: 0,
|
|
SendTimestamp: timestamppb.Now(),
|
|
Type: pb.PeerMessageType_PEER_MESSAGE_TYPE_REQUEST,
|
|
Uid: "test uid",
|
|
}
|
|
buf, err := proto.Marshal(pm)
|
|
if err != nil {
|
|
fmt.Printf("err: %v\n", err)
|
|
} else {
|
|
_, _ = conn.WriteToUDP(buf, broadcast_addr)
|
|
}
|
|
time.Sleep(5 * time.Second)
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
listenAddr, err := net.ResolveUDPAddr("udp4", ":8829")
|
|
if err != nil {
|
|
fmt.Printf("ResolveUDPAddr failed. %v\n", err)
|
|
return
|
|
}
|
|
broadcastServer, err := net.ListenUDP("udp4", listenAddr)
|
|
if err != nil {
|
|
fmt.Printf("ListenUDP Failed. %v\n", err)
|
|
return
|
|
}
|
|
defer broadcastServer.Close()
|
|
fmt.Printf("Server Started.\n")
|
|
|
|
ctx := context.Background()
|
|
go LANServer(ctx, broadcastServer)
|
|
go LANClient(ctx, broadcastServer)
|
|
select {
|
|
case <-ctx.Done():
|
|
fmt.Printf("ctx Done: %v", <-ctx.Done())
|
|
}
|
|
}
|