1. 程式人生 > >golang採用udp實現telnet的功能

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種不同功能.