[Go] 轻量服务器框架基础TCP服务模块

框架要先把整体的结构定义好,一般都是在$GOPATH目录的src下建立自己的目录

[Go] 轻量服务器框架基础TCP服务模块_第1张图片

 

 zinterface是一些接口的定义

znet就是接口的具体实现

IServer.go

package zinterface

type IServer interface{
    Start()
    Stop()
    Server()
}

server.go一个tcp服务端的基本业务,简单的原样回显

package znet

import (
    "fmt"
    "log"
    "net"
    "zinx/zinterface"
)

type Server struct {
    Name      string
    IP        string
    IPversion string
    Port      int
}

func (s *Server) Start() {
    log.Printf("%s %s:%d start...\n", s.Name, s.IP, s.Port)
    addr, err := net.ResolveTCPAddr(s.IPversion, fmt.Sprintf("%s:%d", s.IP, s.Port))
    if err != nil {
        log.Println("resolve tcp addr err ", err)
        return
    }
    listener, err := net.ListenTCP(s.IPversion, addr)
    if err != nil {
        log.Println("listen tcp err ", err)
        return
    }
    go func() {
        for {
            conn, err := listener.AcceptTCP()
            if err != nil {
                log.Println("accept tcp err ", err)
                continue
            }
            go func() {

                for {
                    b := make([]byte, 512)
                    len, err := conn.Read(b)
                    if err != nil {
                        log.Println("read tcp err ", err)
                        continue
                    }
                    if _, err := conn.Write(b[:len]); err != nil {
                        log.Println("write tcp err ", err)
                        continue
                    }
                }
            }()
        }
    }()

}
func (s *Server) Stop() {

}
func (s *Server) Server() {
    s.Start()
    select{}
}
func NewServer(name string) zinterface.IServer {
    s := &Server{
        Name:      name,
        IP:        "0.0.0.0",
        IPversion: "tcp4",
        Port:      8999,
    }
    return s
}

单独在src下创建测试目录

 

 server.go

package main

import (
    "zinx/znet"
)
func main()  {
    server:=znet.NewServer("[zinx]")
    server.Server()
}

 

你可能感兴趣的:([Go] 轻量服务器框架基础TCP服务模块)