golang代码片段(摘抄)

以下是从golang并发编程实战2中摘抄过来的代码片段,主要是实现一个简单的tcp socket通讯(客户端发送一个数字,服务端计算该数字的立方根然后返回),写的不错,用到了go的并发以及看下郝林大神是如何处理socket通讯的。具体代码记录如下,多看多学习多共勉:

package main

import (
	"net"
	"strings"
	"fmt"
	"time"
	"io"
	"bytes"
	"strconv"
	"math"
	"math/rand"
	"sync"
)
const (
	SERVER_NETWORK = "tcp"
	SERVER_ADDRESS = "127.0.0.1:8085"
	DELIMITER = '\t'
)

var wg sync.WaitGroup

func main() {
	wg.Add(2)
	go serverGo()
	time.Sleep(500 * time.Millisecond)
	go clientGo(1)
	wg.Wait()
}

func serverGo() {
	defer wg.Done()
	listener, err := net.Listen(SERVER_NETWORK, SERVER_ADDRESS)
	if err != nil {
		printServerLog("Listen Error: %s", err)
		return
	}
	defer listener.Close()
	printServerLog("Got listener for the server.(local address: %s)", listener.Addr())
	for {
		conn, err := listener.Accept()
		if err != nil {
			printServerLog("Accept Error: %s", err)
		}
		printServerLog("Established a connection with a client application,(remote address: %s)", conn.RemoteAddr())
		go handleConn(conn)
	}
}

func printLog(role string, sn int, format string, args ...interface{})  {
	if !strings.HasSuffix(format, "\n") {
		format += "\n"
	}
	fmt.Printf("%s[%d]: %s", role, sn, fmt.Sprintf(format, args...))
}

func printServerLog(format string, args ...interface{})  {
	printLog("Server", 0, format, args...)
}

func printClientLog(sn int, format string, args ...interface{})  {
	printLog("Cient", sn, format, args...)
}

func handleConn(conn net.Conn)  {
	defer conn.Close()
	for {
		conn.SetDeadline(time.Now().Add(10 * time.Second))		// set read timeline 10s
		strReq, err := read(conn)
		if err != nil {
			if err == io.EOF {
				printServerLog("The connection is closed by another side.")
			} else {
				printServerLog("Read Error: %s", err)
			}
			break
		}
		printServerLog("Received request: %s", strReq)
		intReq, err := strToInt32(strReq)
		if err != nil {
			n, err := write(conn, err.Error())
			printServerLog("Sent error message (written %d bytes): %s", n, err)
			continue
		}
		floatResp := cbrt(intReq)
		respMsg := fmt.Sprintf("The cube root of %d is %f.", intReq, floatResp)
		n, err := write(conn, respMsg)
		if err != nil {
			printServerLog("Sent response message (written %d bytes: %s).", n, respMsg)
		}
	}
}

func read(conn net.Conn) (string, error){
	readBytes := make([]byte, 1)
	var buffer bytes.Buffer
	for {
		_, err := conn.Read(readBytes)
		if err != nil {
			return "", err
		}
		readByte := readBytes[0]
		if readByte == DELIMITER {
			break
		}
		buffer.WriteByte(readByte)
	}
	return buffer.String(), nil
}

func strToInt32(str string) (int32, error){
	i32, err := strconv.ParseInt(str, 10 ,32)
	return int32(i32), err
}

func write(conn net.Conn, content string) (int, error) {
	var buffer bytes.Buffer
	buffer.WriteString(content)
	buffer.WriteByte(DELIMITER)
	return conn.Write(buffer.Bytes())
}

func cbrt(intReq int32) float64 {
	return math.Cbrt(float64(intReq))
}

func clientGo(id int)  {
	defer wg.Done()
	conn, err := net.DialTimeout(SERVER_NETWORK, SERVER_ADDRESS, 2 * time.Second)
	if err != nil {
		printClientLog(id, "Dial Error: %s", err)
		return
	}
	defer conn.Close()
	printClientLog(id, "Connected to server.(remote address: %s,local address: %s)", conn.RemoteAddr(), conn.LocalAddr())
	time.Sleep(200 * time.Millisecond)

	requestNumber := 5
	conn.SetDeadline(time.Now().Add(5 * time.Millisecond))
	for i := 0; i< requestNumber; i++ {
		req := rand.Int31()
		n, err := write(conn, fmt.Sprintf("%d", req))
		if err != nil {
			printClientLog(id, "Write Error: %s", err)
			continue
		}
		printClientLog(id, "Sent request (written %d bytes)", n)
	}
	for j := 0; j< requestNumber; j++ {
		strResp, err := read(conn)
		if err != nil {
			if err == io.EOF {
				printClientLog(id, "The connection is closed by another side.")
			}else{
				printClientLog(id, "Read Error: %s", err)
			}
			break
		}
		printClientLog(id, "Received response: %s", strResp)
	}
}

执行效果:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏比原链

剥开比原看代码02:比原启动后去哪里连接别的节点

Gitee地址:https://gitee.com/BytomBlockchain/bytom

742
来自专栏熊二哥

快速入门系列--WCF--03RESTFUL服务与示例

之前介绍了基于SOAP的Web服务,接下来将介绍基于REST的轻量级的Web服务。 ? REST(Representational State Transfe...

1817
来自专栏陈纪庚

SPA初试-1

即每一个页面对应着一个状态,一个状态有一个状态名,还有一个模板/模板url,这样我们就可以将不同页面的内容写到不同的html里,然后通过templateUrl将...

711
来自专栏Golang语言社区

Go 语言实现的网络连接池:Pool

Pool是一个线程安全,针对net.Conn接口的连接池。它可用于管理和复用网络连接。 示例: // create a factory() to be used...

2714
来自专栏鬼谷君

09-部署配置kubedns插件

1012
来自专栏杨建荣的学习笔记

DBCA静默建库中的两个小问题 (r9笔记第28天)

创建数据库,主要有手工建库,DBCA建库,OMF建库。手工建库会重新初始化数据字典,过程相对比较耗时,但是完全定制化;OMF建库的场景比较特别, 一般都是糅合在...

3274
来自专栏blackpiglet

Ceph 磁盘损坏现象和解决方法

对于存储系统,磁盘是消耗品,损坏是很常见的,所以这篇文章记录一下 Ceph 中出现磁盘损坏时的现象,以及如何定位和更换损坏的磁盘。

672
来自专栏.NET开发者社区

(码友推荐)2018-07-11 .NET及相关开发资讯速递

3.Create Documentation With Sandcastle Help Builde

912
来自专栏一个默默无闻的工程师的日常

centos7 devstack 安装openstack liberty

973
来自专栏逸鹏说道

★Kali信息收集★8.Nmap :端口扫描

突然发现,微信一次最多推送8篇 参数:(Zenmap是Nmap图形化工具,不想打指令的可以直接使用) 详细:https://nmap.org/man/zh/in...

3734

扫码关注云+社区