You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Victorique/vtqe/udp.go

127 lines
2.8 KiB
Go

4 years ago
package main
import (
"fmt"
"net"
"strconv"
"strings"
"time"
"b612.me/starainrt"
"b612.me/starlog"
"github.com/spf13/cobra"
)
var udpcmd = &cobra.Command{
Use: "udp",
Short: "发送并监听udp数据包",
Long: "发送并监听udp数据包",
Run: func(this *cobra.Command, args []string) {
var raddr *net.UDPAddr
r, _ := this.Flags().GetBool("recvonly")
if len(args) != 1 && !r {
fmt.Println("请指定远程udp地址")
return
}
l, _ := this.Flags().GetString("port")
a, _ := this.Flags().GetString("addr")
s, _ := this.Flags().GetBool("local")
b, _ := this.Flags().GetBool("byte")
laddr, err := net.ResolveUDPAddr("udp", a+":"+l)
if !r {
raddr, err = net.ResolveUDPAddr("udp", args[0])
}
if err != nil {
fmt.Println(err)
return
}
if s {
udplisten, err := net.ListenUDP("udp", laddr)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("监听已建立")
go func() {
for {
buf := make([]byte, 204800)
n, addr, err := udplisten.ReadFromUDP(buf)
if err != nil {
starlog.Errorln("Error from %s Where Message=%s\n", addr.String(), err.Error())
continue
}
starlog.Infof("Receive Msg From %s : %s\n", addr.String(), string(buf[0:n]))
if b {
starlog.Infof("%#v\n", buf[0:n])
}
}
}()
}
if !r {
myudp, err := net.DialUDP("udp", nil, raddr)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("UDP虚拟连接已建立")
go func() {
var err error
for {
txt := starainrt.MessageBox("", "")
if txt == "" {
continue
}
if !b {
_, err = myudp.Write([]byte(txt))
} else {
var sendbyte []byte
bytes := strings.Split(txt, ",")
for _, v := range bytes {
ints, _ := strconv.Atoi(v)
if ints < 0 || ints > 255 {
continue
}
sendbyte = append(sendbyte, byte(ints))
}
_, err = myudp.Write(sendbyte)
}
if err != nil {
fmt.Printf("Error from %s Where Message=%s\n", myudp.RemoteAddr().String(), err.Error())
return
}
}
}()
for {
buf := make([]byte, 204800)
n, err := myudp.Read(buf)
if err != nil {
starlog.Infof("Error from %s Where Message=%s\n", myudp.RemoteAddr().String(), err.Error())
return
}
starlog.Infof("Receive Msg From %s : %s\n", myudp.RemoteAddr().String(), string(buf[0:n]))
if b {
starlog.Infof("%#v", buf[0:n])
}
}
} else {
for {
time.Sleep(time.Second)
}
}
},
}
/*
*/
func init() {
udpcmd.Flags().BoolP("byte", "b", false, "发送二进制数据")
udpcmd.Flags().StringP("port", "p", "1127", "本地监听端口")
udpcmd.Flags().StringP("addr", "a", "0.0.0.0", "本地监听ip")
udpcmd.Flags().BoolP("local", "s", false, "启动本地监听")
udpcmd.Flags().BoolP("recvonly", "r", false, "仅接收udp包")
}