Go教程

go语言之TCP编程

本文主要是介绍go语言之TCP编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

demo1

  • server
package main

import (
	"fmt"
	"net"
	"os"
	"strconv"
	"time"
)

func CheckError(err error){
	if err != nil{
		fmt.Println(err)
		os.Exit(1)
	}
}

func main() {
	ip := "127.0.0.1"
	port := 5656
	tcpAddr, err := net.ResolveTCPAddr("tcp4", ip+":"+strconv.Itoa(port))
	CheckError(err)
	listener, err := net.ListenTCP("tcp4", tcpAddr)
	CheckError(err)
	fmt.Println("waiting for client connnetion......")
	conn, err := listener.Accept()
	CheckError(err)
	fmt.Printf("establish connnection to client %s\n", conn.RemoteAddr().String())
	request := make([]byte, 256)
	_, err = conn.Read(request)
	CheckError(err)
	fmt.Printf("receive request %s\n", string(request))
	n, err := conn.Write([]byte("hello "+ string(request)))
	CheckError(err)
	fmt.Printf("write response %d bytes\n", n)
	time.Sleep(1 * time.Second)
	_, err = conn.Write([]byte("oops"))
	CheckError(err)
}
  • client
package main

import(
	"net"
	"fmt"
	"strconv"
	"os"
)

func CheckError(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func main() {
	ip := "127.0.0.1"
	port := 5656
	tcpAddr, err := net.ResolveTCPAddr("tcp4", ip+":"+strconv.Itoa(port))
	CheckError(err)
	fmt.Printf("ip %s port %v\n", tcpAddr.IP.String(), tcpAddr.Port)
	conn, err := net.DialTCP("tcp4", nil ,tcpAddr)
	CheckError(err)
	fmt.Printf("establish connnection to server %s\n",conn.RemoteAddr().String())
	n, err := conn.Write([]byte("china"))
	CheckError(err)
	fmt.Printf("write request %d\n", n)
	response := make([]byte, 256)
	_, err = conn.Read(response)
	CheckError(err)
	fmt.Printf("receive response: %s\n", string(response))
	conn.Close()
}
这篇关于go语言之TCP编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!