微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Go]TCP服务中读写进行协程分离

读写两部分进行一下分离,中间通过chan进行传递数据 ,这样可以方便的在write中进行一些业务处理

 

single/snet/tcpconn.go

package snet

import (
    "bufio"
    fmtlognet"
)

type Conn struct {
    IP       string
    Port     uint32
    TCPConn  *net.TCPConn
    MsgChan  chan []byte
    ExitChan chan bool
    Closed   
}

func NewConn(IP string,Port uint32) *Conn {
    s := &Conn{
        IP:   IP,Port: Port,MsgChan:make(chan []),ExitChan: make(chan Conn) Start() {
    log.Printf(%s:%d start...\n,c.IP,c.Port)
    go func() {
        addr,err := net.ResolveTCPAddr(tcp4",fmt.Sprintf(%s:%dif err != nil {
            log.Println(resolve tcp addr err listen tcp err 0
        for {
            conn,err := listener.AcceptTCP()
             nil {
                log.Println(accept tcp err  conn
            go c.StartRead()
            go c.StartWrite()
            connid++
        }
    }()
    select {}
}
func (c *Conn) StartRead() {
    log.Println(read groutine is waiting)
    defer c.Stop()
    defer log.Println(read groutine exit)
    reader := bufio.NewReader(c.TCPConn)
     {
        lineBytes,err := reader.ReadBytes('\n')
        startread read bytes error len(lineBytes)
        line:=lineBytes[:len-1]
        log.Println(start read from client (line))
        go c.HandleMsg(line)
    }
}
func (c *Conn) StartWrite() {
    log.Println(write groutine is waiting)
    defer log.Println(write groutine exit)
     {
        case data := <-c.MsgChan:
            if _,err := c.TCPConn.Write(data); err !=startwrite conn write error start write from server (data))
        case <-c.ExitChan:
            return
        }
    }
}
func (c *Conn) HandleMsg(data []) {
    res := res:%s(data))


    c.MsgChan <- [](res)
}
func (c *Conn) Stop() {
    if c.Closed {
        return
    }
    c.Closed = true
    c.ExitChan <- 

    c.TCPConn.Close()
    close(c.ExitChan)
    close(c.MsgChan)
}

测试代码,使用上面的包:

server.go

package main

import single/snet
func main(){
    s:=snet.NewConn(0.0.0.08777)
    s.Start()
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐