GO语言UDP小笔记

前端之家收集整理的这篇文章主要介绍了GO语言UDP小笔记前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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,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,70})
	}
}
原文链接:https://www.f2er.com/go/190269.html

猜你在找的Go相关文章