Go tcp通信

//server端

<pre name="code" class="cpp">package main

import (
	"fmt"
	"net"
	"os"
	"strconv"
	"strings"
	"time"
	//"io/ioutil"
)

func main() {
	service := "localhost:7777"
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkError(err)
	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)
	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		go handleClient(conn)
	}
}

func handleClient(conn net.Conn) {
	//设置了超时,当一定时间内客户端无请求发送,conn便会自动关闭,下面的for循环即会因为连接已关闭而跳出(即socket断开)
	conn.SetReadDeadline(time.Now().Add(3 * time.Second)) // set 2 minutes timeout
	request := make([]byte, 128)                          // set maxium request length to 128B to prevent flood attack
	defer conn.Close()                                    // close connection before exit
	for {
		read_len, err := conn.Read(request)
		fmt.Println("------")
		a := len(request)
		fmt.Println(string(request))
		fmt.Println(a)
		fmt.Println("******")
		fmt.Println(string(request[:read_len]))
		fmt.Println(read_len)

		if err != nil {
			fmt.Println(err)
			break
		}

		if read_len == 0 {
			break // connection already closed by client
		} else if strings.TrimSpace(string(request[:read_len])) == "timestamp" {
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}

		request = make([]byte, 128) // clear last read content
	}
}

func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}


 

//client端
<pre name="code" class="cpp">package main

import (
	"fmt"
	"io/ioutil"
	"net"
	"os"
)

func main() {
	service := "localhost:7777"
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkError(err)
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	checkError(err)
	_, err = conn.Write([]byte("hello"))
	checkError(err)
	//注意ioutil.ReadAll和conn.Read
	//区别参考http://www.golangtc.com/t/53b7a47d320b522f430000b2
	result, err := ioutil.ReadAll(conn)
	//request := make([]byte, 128)
	//read_len, err := conn.Read(request)
	checkError(err)
	//fmt.Println(string(request[:read_len]))
	//conn.Close()
	fmt.Println(string(result))
	os.Exit(0)
}
func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}

[gfj@kfjk2 bin]$ ./tcp_server 
------
hello
128
******
hello
5
------


128
******


0
read tcp 127.0.0.1:7777->127.0.0.1:31020: i/o timeout
 

[gfj@kfjk2 bin]$ ./tcp_client 
2016-08-11 21:30:19.799264092 +0800 CST

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值