package main

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

type Mail struct {
    clientName string
    from       string
    to         string
    data       string
    reciveData bool
}

func main() {

    listen, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("127.0.0.1"), 25, ""})
    if err != nil {
        fmt.Println("监听端口失败:", err.Error())
        return
    }
    defer listen.Close()
    recive(listen)

}

func recive(listen *net.TCPListener) {

    for {
        conn, err := listen.AcceptTCP() //接收连接
        defer conn.Close()
        if err != nil {
            fmt.Println("客户端连接异常", err.Error()) //客户端连接异常
            continue
        }
        conn.Write([]byte("220 GoMailSever "))
        fmt.Println("新客户端", conn.RemoteAddr().String())
        go func() {

            tmpBuffer := make([]byte, 0)           //创建待处理字节切片
            readerChannel := make(chan []byte, 16) //创建channel通信管道
            _mail := &Mail{}
            go reader(readerChannel, conn, _mail) //channel信息接收端
            data := make([]byte, 1024)            //创建输出缓冲切片

            for {
                i, err := conn.Read(data) //从Socket读取数据
                if err != nil {
                    fmt.Println("读取发生错误", err.Error()) //读取失败发生错误
                    return
                }
                tmpBuffer = DepackMail(append(tmpBuffer, data[:i]...), readerChannel) //用自定义协议处理字节

                //fmt.Println(data, string(data))
            }

        }()

    }
}
func reader(readerChannel chan []byte, conn *net.TCPConn, _mail *Mail) {

    for {
        select {
        case data := 

文章来源于互联网:golang编写SMTP邮箱服务端

发表评论