[GoLang]GO語言編寫的簡易TCP服務端、用戶端

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

用戶端程式:

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}}}}}

服務端:


用戶端:


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.