golang采用udp实现telnet的功能

udp实现了个跨平台的telnet小程序,用来测试基于udp的消息收发.

代码如下:

package main

import (
	"fmt"
	"flag"
	"net"
	"strconv"
	"bufio"
	"os"
)
func write(listener *net.UDPConn,dstAddr *net.UDPAddr) {
	for {
		bio := bufio.NewReader(os.Stdin)
		buf,_,_:= bio.ReadLine()
		listener.WriteToUDP(buf, dstAddr)
	}
}
func read(listener *net.UDPConn) {
	for {
		buf :=make([]byte, 1400)
		size, remote, err := listener.ReadFromUDP(buf)
		if err != nil {
			fmt.Printf("error during read: %s", err)
		}
		fmt.Println("recv:", string(buf[:size]), " from ", remote.String())
	}
}
func run(lport *string , ip *string , sport *string) {
	port,err:=strconv.Atoi(*lport)
	addr := &net.UDPAddr{IP: net.ParseIP("0.0.0.0"), Port:port }
	port,err =strconv.Atoi(*sport)
	dstAddr := &net.UDPAddr{IP: net.ParseIP(*ip), Port: port}
	listener, err := net.ListenUDP("udp", addr)
	defer listener.Close()
	if err != nil {
		fmt.Println(err, " recv udp ", port)
		return
	}
	//send to its subs
	go read(listener)
	go write(listener, dstAddr)
	select{}
}
func main(){
	lport := flag.String("lport", "40109", "udp listen port")
	ip := flag.String("ip", "0.0.0.0", "udp send ip")
	sport := flag.String("sport", "40109", "udp send port")

	flag.Parse()
	fmt.Println("listen port:", *lport)
	fmt.Println("send ip", *ip)
	fmt.Println("send port:", *sport)
	run(lport,ip,sport)
}

main函数中,实现了命令手册的功能,有3个参数,本地监听端口,目标ip和端口.

在read函数中,将收到的网络数据,按行显示.

在write函数中,按行从命令行读入,通过网络发送到对端.

测试可以直接本地回显,也可以多程序启动,实现点对点,广播等更复杂的形式.

用法如下:

go build main.go
./main -lport 1234 -sport 4567 -ip 192.168.1.15
./main -h
./main

以上3项测试来完成3种不同功能.

你可能感兴趣的:(go)