本文整理汇总了Golang中net.TCPConn.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang TCPConn.Close方法的具体用法?Golang TCPConn.Close怎么用?Golang TCPConn.Close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.TCPConn
的用法示例。
在下文中一共展示了TCPConn.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handler
// handler handles a single TCP Connection
func (t *TcpListener) handler(conn *net.TCPConn, id string) {
// connection cleanup function
defer func() {
t.wg.Done()
conn.Close()
log.Printf("Closed TCP Connection from %s", conn.RemoteAddr())
// Add one connection potential back to channel when this one closes
t.accept <- true
t.forget(id)
}()
scanner := bufio.NewScanner(conn)
for {
select {
case <-t.done:
return
default:
if !scanner.Scan() {
return
}
buf := scanner.Bytes()
select {
case t.in <- buf:
default:
log.Printf(dropwarn, string(buf))
}
}
}
}
示例2: serve
func serve(conn *net.TCPConn, fileS *File_Server, uid int) {
reader := bufio.NewReader(conn)
for {
msg, msgerr, fatalerr := fs.GetMsg(reader)
if fatalerr != nil || msgerr != nil {
reply(conn, &fs.Msg{Kind: 'M'})
conn.Close()
break
}
if msgerr != nil {
if (!reply(conn, &fs.Msg{Kind: 'M'})) {
conn.Close()
break
}
}
newchannel := make(chan *fs.Msg, 1)
mutex.Lock()
fileS.Msgcount = fileS.Msgcount + 1
count := fileS.Msgcount
fileS.Channels[count] = newchannel
fmt.Println("Listening at", count)
mutex.Unlock()
modified_msg := Message{uid, count, *msg} // We are adding message id with it.
newmsg, _ := json.Marshal(modified_msg)
fileS.Raft.Append(newmsg)
for {
select {
case ci := <-fileS.Channels[count]:
reply(conn, ci)
}
break
}
}
}
示例3: handleConnection
// 分配连接处理
func (self *AgentSvr) handleConnection(conn *net.TCPConn) {
defer conn.Close()
defer self.wg.Done()
defer func() {
if err := recover(); err != nil {
Error("handle agent connection:%v failed:%v", conn.RemoteAddr(), err)
}
}()
Info("new agent connection:%v", conn.RemoteAddr())
for {
var sz uint32
err := binary.Read(conn, binary.BigEndian, &sz)
if err != nil {
Error("read conn failed:%v, err:%v", conn.RemoteAddr(), err)
break
}
buf := make([]byte, sz)
_, err = io.ReadFull(conn, buf)
if err != nil {
Error("read conn failed:%v, err:%v", conn.RemoteAddr(), err)
break
}
var req Request
if err = json.Unmarshal(buf, &req); err != nil {
Error("parse request failed:%v, err:%v", conn.RemoteAddr(), err)
}
go self.dispatchRequst(conn, &req)
}
}
示例4: handleConnection
func (this *HttpProxyServer) handleConnection(conn *net.TCPConn) {
defer conn.Close()
reader := bufio.NewReader(conn)
request, err := http.ReadRequest(reader)
if err != nil {
log.Warning("Failed to read http request: ", err)
return
}
log.Info("Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
defaultPort := v2net.Port(80)
if strings.ToLower(request.URL.Scheme) == "https" {
defaultPort = v2net.Port(443)
}
host := request.Host
if len(host) == 0 {
host = request.URL.Host
}
dest, err := parseHost(host, defaultPort)
if err != nil {
log.Warning("Malformed proxy host (", host, "): ", err)
return
}
if strings.ToUpper(request.Method) == "CONNECT" {
this.handleConnect(request, dest, reader, conn)
} else {
this.handlePlainHTTP(request, dest, reader, conn)
}
}
示例5: proxy
func proxy(cliConn *net.TCPConn, rAddr *net.TCPAddr) error {
srvConn, err := net.DialTCP("tcp", nil, rAddr)
if err != nil {
cliConn.Close()
return err
}
defer srvConn.Close()
// channels to wait on the close event for each connection
serverClosed := make(chan struct{}, 1)
clientClosed := make(chan struct{}, 1)
go broker(srvConn, cliConn, clientClosed)
go broker(cliConn, srvConn, serverClosed)
var waitFor chan struct{}
select {
case <-clientClosed:
// the client closed first
srvConn.SetLinger(0)
srvConn.CloseRead()
waitFor = serverClosed
case <-serverClosed:
cliConn.CloseRead()
waitFor = clientClosed
}
<-waitFor
return nil
}
示例6: handleConnection
func handleConnection(conn *net.TCPConn) error {
defer conn.Close()
handlerChan <- 1
defer func() {
handlerChan <- -1
}()
var ws *websocket.Conn
conn.SetDeadline(time.Now().Add(socksTimeout))
err := AwaitSocks4aConnect(conn, func(dest string) (*net.TCPAddr, error) {
// Disable deadline.
conn.SetDeadline(time.Time{})
Log("SOCKS request for %s", dest)
destAddr, err := net.ResolveTCPAddr("tcp", dest)
if err != nil {
return nil, err
}
wsUrl := url.URL{Scheme: "ws", Host: dest}
ws, err = websocket.Dial(wsUrl.String(), "", wsUrl.String())
if err != nil {
return nil, err
}
Log("WebSocket connection to %s", ws.Config().Location.String())
return destAddr, nil
})
if err != nil {
return err
}
defer ws.Close()
proxy(conn, ws)
return nil
}
示例7: serveTCP
func (server *Server) serveTCP(conn *net.TCPConn, rrp, wrp *sync.Pool, rr *bufio.Reader, wr *bufio.Writer, tr *Timer) {
var (
b *Bucket
p *Proto
hb time.Duration // heartbeat
key string
err error
trd *TimerData
ch = NewChannel(Conf.CliProto, Conf.SvrProto)
pb = make([]byte, maxPackIntBuf)
)
// auth
if trd, err = tr.Add(Conf.HandshakeTimeout, conn); err != nil {
log.Error("handshake: timer.Add() error(%v)", err)
goto failed
}
key, hb, err = server.authTCP(rr, wr, pb, ch)
tr.Del(trd)
if err != nil {
log.Error("server.authTCP() error(%v)", err)
goto failed
}
// register key->channel
b = server.Bucket(key)
b.Put(key, ch)
// hanshake ok start dispatch goroutine
go server.dispatchTCP(conn, wrp, wr, ch, hb, tr)
for {
// fetch a proto from channel free list
if p, err = ch.CliProto.Set(); err != nil {
log.Error("%s fetch client proto error(%v)", key, err)
goto failed
}
// parse request protocol
if err = server.readTCPRequest(rr, pb, p); err != nil {
log.Error("%s read client request error(%v)", key, err)
goto failed
}
// send to writer
ch.CliProto.SetAdv()
ch.Signal()
}
failed:
// dialog finish
// may call twice
if err = conn.Close(); err != nil {
log.Error("reader: conn.Close() error(%v)")
}
PutBufioReader(rrp, rr)
if b != nil {
b.Del(key)
log.Debug("wake up dispatch goroutine")
ch.Finish()
}
if err = server.operator.Disconnect(key); err != nil {
log.Error("%s operator do disconnect error(%v)", key, err)
}
log.Debug("%s serverconn goroutine exit", key)
return
}
示例8: serve
// serve serves a single accepted connection
func (p *proxy) serve(client *net.TCPConn) {
connected := connectedClients.With(p.labels)
connected.Inc()
defer func() {
connected.Dec()
_ = client.Close()
}()
p.mutex.Lock()
upstreams := make([]Upstream, len(p.upstreams))
copy(upstreams, p.upstreams)
p.mutex.Unlock()
// TODO: proper iterator accounting weights and current # of connections
for i := range upstreams {
j := rand.Intn(i + 1)
upstreams[i], upstreams[j] = upstreams[j], upstreams[i]
}
for _, upstream := range upstreams {
p.log(fmt.Sprintf("connecting from %s to %s", client.RemoteAddr(), upstream))
backend, err := net.Dial("tcp", upstream.Addr())
if err != nil {
p.log(fmt.Sprintf("error connecting from %s to %s: %s", client.RemoteAddr(), upstream.Addr(), err))
connectionErrors.With(prometheus.Labels{"app": p.app, "upstream": upstream.Addr()}).Inc()
continue
}
p.proxyLoop(client, backend.(*net.TCPConn))
break
}
}
示例9: handleHost
func handleHost(conn *net.TCPConn) {
defer conn.Close()
defer fmt.Printf("Closed host conn.\n")
w := bufio.NewWriter(conn)
name_line := make([]byte, 32)
n, err := conn.Read(name_line)
if err != nil {
// TODO: Log this error
fmt.Printf("Failed to read game from host: %v\n", err)
return
}
name := strings.TrimSpace(string(name_line[0:n]))
fmt.Printf("Game name: '%s': %d\n", name, len(name))
if !registerGame(name, conn) {
w.Write([]byte(fmt.Sprintf("Unable to make game '%s', that name is already in use.\n", name)))
return
}
defer unregisterGame(name)
w.Flush()
game := getGame(name)
game.Run()
}
示例10: handleConnection
func (proxy *Proxy) handleConnection(in *net.TCPConn) error {
defer in.Close()
plainOut, err := proxy.connectionFactory()
if err != nil {
log.Print("could no create outgoing connection", err)
return err
}
out := plainOut.(*net.TCPConn)
defer out.Close()
serverClosed := make(chan struct{}, 1)
clientClosed := make(chan struct{}, 1)
go broker(out, in, clientClosed)
go broker(in, out, serverClosed)
var waitFor chan struct{}
select {
case <-clientClosed:
// the client closed first and any more packets from the server aren't
// useful, so we can optionally SetLinger(0) here to recycle the port
// faster.
out.SetLinger(0)
out.CloseRead()
waitFor = serverClosed
case <-serverClosed:
in.CloseRead()
waitFor = clientClosed
}
<-waitFor
return nil
}
示例11: handleClient
func handleClient(pf *PF, source *net.TCPConn) {
atomic.AddInt32(&pf.status.actives, 1)
defer func() {
atomic.AddInt32(&pf.status.actives, -1)
pf.wg.Done()
}()
settings := pf.settings
host := chooseHost(settings.weight, settings.Hosts)
if host == nil {
source.Close()
logger.Println("choose host failed")
return
}
dest, err := net.DialTCP("tcp", nil, host.addr)
if err != nil {
source.Close()
logger.Printf("connect to %s failed: %s", host.addr, err.Error())
return
}
source.SetKeepAlive(true)
source.SetKeepAlivePeriod(time.Second * 60)
source.SetLinger(-1)
dest.SetLinger(-1)
go forward(source, dest)
forward(dest, source)
//logger.Printf("forward finished, %v -> %v", source.RemoteAddr(), host)
}
示例12: forward
func forward(source *net.TCPConn, dest *net.TCPConn) {
defer func() {
dest.Close()
}()
bufsz := 1 << 12
cache := make([]byte, bufsz)
for {
// pump from source
n, err1 := source.Read(cache)
// pour into dest
c := 0
var err2 error
for c < n {
i, err2 := dest.Write(cache[c:n])
if err2 != nil {
break
}
c += i
}
if err1 != nil || err2 != nil {
break
}
}
}
示例13: getData
// Demo goroutine start, but main goroutine exit, which kills the connection.
// Not useful, but indicates how connections work.
// 'Tested' using 'telnet localhost 45678'
func getData(tcpConn *net.TCPConn, done chan bool) {
for {
var buffer = make([]byte, 256)
fmt.Println("Starting Read ...")
bytesRead, err := tcpConn.Read(buffer)
if err != nil {
fmt.Printf("Error = %v\n", err)
break
}
//
fmt.Println("Bytes Read", tcpConn, bytesRead)
bufData := buffer[0:bytesRead]
fmt.Println("Buffer", tcpConn, bufData)
var data = string(bufData)
fmt.Println("Data Read", tcpConn, data)
//
if strings.HasPrefix(data, "quit") {
break
}
}
//
fmt.Println("Starting Close() 1")
err := tcpConn.Close()
if err != nil {
fmt.Printf("Error = %v\n", err)
panic("wtf05")
}
//
done <- true
}
示例14: serve
func serve(con *net.TCPConn) {
defer con.Close()
if *verbose {
fmt.Fprintf(os.Stdout, "serving %s\n", con.RemoteAddr().String())
}
for {
line, err := readUntilCrLf(con)
if err != nil {
// TODO : pass error message
con.Write([]byte("\"internal error\"\r\n"))
continue
}
tokens := strings.Split(string(line), " ", -1)
command := tokens[0]
if command == "quit" {
writeJson(con, "bye.")
break
}
f, ok := commands[command]
if ok {
f(con, tokens[1:])
} else {
writeJson(con, fmt.Sprintf("unknown command '%s'", command))
}
}
}
示例15: ReadTCPChannel
func ReadTCPChannel(conn *net.TCPConn, delimiter string, fromSocket chan Message) error {
var message string
buffer := make([]byte, socketBuffer)
for {
if n, err := conn.Read(buffer); err != nil || n == 0 {
if n == 0 && err == nil {
err = errors.New("No bytes")
}
myLog.Printf("Closing:%v %v\n", conn.RemoteAddr(), err)
conn.Close()
return err
} else {
message += string(buffer[0:n])
m := strings.Split(message, delimiter)
for i, entry := range m {
if i < len(m)-1 {
fromSocket <- Message{Msg: entry, RemoteAddr: conn.RemoteAddr()}
} else {
// overflow
message = entry
}
}
}
}
return nil
}