這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
用戶端程式:
package mainimport ("net""os""fmt""io")//緩衝區大小const BUFFSIZE = 1024//定義訊息緩衝區var buff = make([]byte, BUFFSIZE)//連結處理func handleConn(tcpConn *net.TCPConn, addr string) {if tcpConn == nil {//fmt.Println()return}for{n, err := tcpConn.Read(buff)if err == io.EOF {fmt.Printf("遠程連結:%s已經關閉!\n", tcpConn.RemoteAddr().String())return}handleError(err)if string(buff[:n]) == "exit" {fmt.Printf("遠程連結:%s退出!\n", tcpConn.RemoteAddr().String())}if n > 0 {fmt.Printf("%s發來訊息:%s", addr, string(buff[:n]))}}}func handleError(err error) {if err == nil {return}fmt.Printf("錯誤:%s\n", err.Error())}func main() {//判斷命令列參數是否錯誤if len(os.Args) != 2 {fmt.Printf("調用參數錯誤,程式中斷!\n")return}//擷取通訊連接埠port := os.Args[1]//原型:func ResolveTCPAddr(net, addr string) (*TCPAddr, error) ResolveTCPAddr parses addr as a TCP address//分解ip為TCP地址tcpAddr, err := net.ResolveTCPAddr("tcp4", "localhost:" + port)handleError(err)if err != nil {return}//原型:func ListenTCP(net string, laddr *TCPAddr) (*TCPListener, error) ListenTCP announces on the TCP address laddr and returns a TCP listener.//通過TCP地址返回一個TCP監聽tcpListener, err := net.ListenTCP("tcp4", tcpAddr)handleError(err)if err != nil {return}fmt.Printf("啟動監聽,等待連結!\n")//延遲,監聽關閉defer tcpListener.Close()for {//func (l *TCPListener) AcceptTCP() (*TCPConn, error) AcceptTCP accepts the next incoming call and returns the new connection.//等待下一個訪問並返回一個新連結tcpConn, err := tcpListener.AcceptTCP()handleError(err)if err != nil {return}fmt.Printf("用戶端:%s已串連!\n", tcpConn.RemoteAddr().String())//延遲,關閉連結defer tcpConn.Close()//啟動一個串連處理線程go handleConn(tcpConn, tcpConn.RemoteAddr().String())}}
服務端程式:
package mainimport ("net""os""fmt""bufio")const BUFFSIZE = 1024var buff = make([]byte, BUFFSIZE)func handleError(err error) {if err == nil {return}fmt.Printf("錯誤:%s\n", err.Error())}func main() {if len(os.Args) != 2 {fmt.Printf("參數錯誤, 程式中斷!\n")return}port := os.Args[1]tcpAddr, err := net.ResolveTCPAddr("tcp4", "localhost:" + port)handleError(err)tcpConn, err := net.DialTCP("tcp4", nil, tcpAddr)handleError(err)fmt.Printf("串連成功,請輸入資訊!\n")reader := bufio.NewReader(os.Stdin)continued := trueinputStr := ""for(continued){n, err := reader.Read(buff)handleError(err)if n > 0 {k, _ := tcpConn.Write(buff[:n])if k > 0 {inputStr = string(buff[:n])fmt.Printf("發送訊息:%s", inputStr)if inputStr == "exit\n" {continued = false}}}}}
服務端:
用戶端: