<pre style="margin-top: 0px; margin-bottom: 0px;"><span style=" color:#0000ff;">package</span><span style=" color:#f57900;"> </span>main
import (
"fmt"
"net"
"time"
)
func main() {
udpaddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:1789")
if err != nil {
fmt.Println(err)
return
}
lis, err := net.ListenUDP("udp", udpaddr)
if err != nil {
fmt.Println(err)
return
}
defer lis.Close()
for {
buf := make([]byte, 512)
n, addr, err := lis.ReadFromUDP(buf)
if err != nil {
fmt.Println(err)
continue
}
str := string(buf[:n])
go func(lis *net.UDPConn, addr *net.UDPAddr, body string) {
lis.WriteToUDP([]byte(body), addr)
time.Sleep(3e9)
}(lis, addr, str)
}
}
package main import ( "bytes" "encoding/json" "fmt" "io" "net" "os" ) type Fileinfo struct { Name string Path string } func server() { laddr := &net.UDPAddr{IP: []byte{127, 0, 0, 1}, Port: 1789} con, err := net.ListenUDP("udp", laddr) if err != nil { fmt.Println(err) return } defer con.Close() for { Buf := make([]byte, 1024) n, raddr, _ := con.ReadFromUDP(Buf) var info Fileinfo json.Unmarshal(Buf[:n], &info) if info.Name != "" { if info.Path != "" { e := os.Chdir(info.Path) if e != nil { con.WriteTo([]byte(e.Error()), raddr) continue } } con.WriteToUDP([]byte("OK"), raddr) File, _ := os.Create(info.Name) defer File.Close() for { Buf := make([]byte, 4096) n, r, _ := con.ReadFromUDP(Buf) if r.String() != raddr.String() { continue } if n == 4 && bytes.Contains([]byte{0, 69, 79, 70}, Buf[:n]) { File.Sync() File.Close() break } File.Write(Buf[:n]) } } } } func client() { con, e := net.Dial("udp", "127.0.0.1:1789") if e != nil { fmt.Println(e) return } defer con.Close() var info Fileinfo = Fileinfo{Name: "WinMD5.exe", Path: "D:"} b, _ := json.Marshal(info) con.Write([]byte(b)) Buf := make([]byte, 1024) n, _ := con.Read(Buf) if string(Buf[:n]) == "OK" { File, _ := os.Open("3.go") for { Buf := make([]byte, 4096) n, e := File.Read(Buf) if e != nil { if e == io.EOF { break } fmt.Println(e) break } con.Write(Buf[:n]) } con.Write([]byte{0, 69, 79, 70}) } }
有疑问加站长微信联系(非本文作者)