Skip to content

Commit

Permalink
part implements gate
Browse files Browse the repository at this point in the history
  • Loading branch information
name5566 committed Aug 10, 2014
1 parent ab231d4 commit 8f12830
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 73 deletions.
3 changes: 3 additions & 0 deletions service/gate/http.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
package gate

type HttpGateExtension interface {
}

type HttpGate struct {
}
83 changes: 55 additions & 28 deletions service/gate/tcp.go
Original file line number Diff line number Diff line change
@@ -1,55 +1,82 @@
package gate

import (
"github.com/name5566/leaf/log"
"net"
"sync"
)

const (
name = "tcpgate"
defAddr = ":8080"
)

type TcpGate struct {
Addr string
ln net.Listener
// you must implement this interface
type TcpGateExtension interface {
}

func NewTcpGate() (*TcpGate, error) {

type TcpGate struct {
ext TcpGateExtension
ln net.Listener
maxConnNum int
conns map[net.Conn]*ConnContext
lConns sync.RWMutex
}

func (tcpGate *TcpGate) Name() string {
return name
type ConnContext struct {
}

func (tcpGate *TcpGate) Start() {
if tcpGate.Addr == "" {
tcpGate.Addr = defAddr
}

ln, err := net.Listen("tcp", tcpGate.Addr)
func NewTcpGate(ext TcpGateExtension, laddr string, maxConnNum int) (*TcpGate, error) {
ln, err := net.Listen("tcp", laddr)
if err != nil {
panic(err)
return nil, err
}

tcpGate := new(TcpGate)
tcpGate.ext = ext
tcpGate.ln = ln
tcpGate.maxConnNum = maxConnNum
return tcpGate, nil
}

func (tcpGate *TcpGate) Start() {
go func() {
for {
// accept conn
conn, err := tcpGate.ln.Accept()
if err != nil {
if err.Error() == "use of closed network connection" {
log.Release("tcp gate closed")
return
} else {
log.Error("accept error: %v", err)
continue
}
}

for {
conn, err := ln.Accept()
if err != nil {
if err.Error() == "use of closed network connection" {
break
} else {
// conns
tcpGate.lConns.Lock()
if len(tcpGate.conns) >= tcpGate.maxConnNum {
tcpGate.lConns.Unlock()
conn.Close()
log.Error("too many connections (%v)", tcpGate.maxConnNum)
continue
}
tcpGate.conns[conn] = new(ConnContext)
tcpGate.lConns.Unlock()

// handle conn
go tcpGate.handleConn(conn)
}
go handleConn(conn)
}
}()
}

func (tcpGate *TcpGate) Close() {
tcpGate.ln.Close()

tcpGate.lConns.Lock()
for conn, _ := range tcpGate.conns {
conn.Close()
}
tcpGate.conns = make(map[net.Conn]*ConnContext)
tcpGate.lConns.Unlock()
}

func handleConn(conn net.Conn) {
func (tcpGate *TcpGate) handleConn(conn net.Conn) {

}
45 changes: 0 additions & 45 deletions service/service.go

This file was deleted.

0 comments on commit 8f12830

Please sign in to comment.