Golang - net.Conn在同一条消息上的无限循环

时间:2016-05-27 08:54:54

标签: sockets go open-closed-principle

我是Golang的新闻,只使用这个版本的套接字2天。但是,我不确定能理解什么。我知道在C中,我使用select()来知道谁写了等等,但是在这里,没有人在写一个消息之前就写了。发送此消息后,我的dialTCP无休止地使用它。

我想我错过了关于close()的一些内容,但我不确定它来自这里......有我的代码:

package dial

import (
"errors"
"encoding/json"
m "models"
"net"
"net/http"
"time"
"server"
)

type DialTCP struct {}

// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe and ListenAndServeTLS so
// dead TCP connections (e.g. closing laptop mid-download) eventually
// go away.
type tcpKeepAliveListener struct {
    *net.TCPListener
}

func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
    tc, err := ln.AcceptTCP()
    if err != nil {
            return
    }
    tc.SetKeepAlive(true)
    tc.SetKeepAlivePeriod(3 * time.Minute)
    return tc, nil
 }

 func (dialTCP *DialTCP) ListenAndServe(addr string) error {
    ln, err := net.Listen("tcp", addr)
    if err != nil {
            return err
    }
    return dialTCP.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
 }

 func (dialTCP *DialTCP) Serve(l net.Listener) error {
    defer l.Close()

    for {
            conn, e := l.Accept()
            if e != nil {
                    return e
            }

            // you want to create server_conn here with buffers, channels and stuff
            // to use async thread safe read/write from it
            go dialTCP.serve_conn(conn)
    }
 }

 func (dialTCP *DialTCP) serve_conn(conn net.Conn) error {
    // var buf [512]byte
    dec := json.NewDecoder(conn)

    //read 1st message he sent, should be token to connect
    var auth m.DialAuthentication
    dec.Decode(&auth)
    user := m.User{
    UUID: auth.UUID,
    }

    ok, sb := server.IsConnected(user)
    if ok == false {
            json.NewEncoder(conn).Encode(sb)
            return errors.New("User isn't connected.")
    } else {
            user.Conn = conn
    }
    //defer conn.Close()

    var message m.DialMessageContainer
    for {
            dec.Decode(&message)

            switch message.Type {
            case ".....":
            /*    ....(message, user)
            case "....":
                ....(message, user)
//          case "...":*/

            default:
                    json.NewEncoder(conn).Encode(m.StatusBack{Description: "Bad entry.", StatusId: http.StatusNotAcceptable})
            }
            //defer conn.Close()
    }
}

我认为在serv_conn()之前一切都很好,但错误应该来自for。我尝试了很多东西,但这对于Golang中的{} ...为什么它没有任何params / var,比如C / C ++ / C#/ Java?

for(int i = 0; i< 10; i ++){}

我也对Conn的关闭感到迷茫,所以我继续阅读关于如何使用它的教程,帖子和文档。天通过whitout找到任何东西

0 个答案:

没有答案