本文整理汇总了Golang中net.Conn.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang Conn.Close方法的具体用法?Golang Conn.Close怎么用?Golang Conn.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.Conn
的用法示例。
在下文中一共展示了Conn.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handleClient
func handleClient(p1, p2 net.Conn) {
log.Println("stream opened")
defer log.Println("stream closed")
defer p1.Close()
defer p2.Close()
// start tunnel
p1die := make(chan struct{})
go func() {
io.Copy(p1, p2)
close(p1die)
}()
p2die := make(chan struct{})
go func() {
io.Copy(p2, p1)
close(p2die)
}()
// wait for tunnel termination
select {
case <-p1die:
case <-p2die:
}
}
示例2: onConn
func (s *Server) onConn(c net.Conn) {
conn := s.newClientConn(c) //新建一个conn
defer func() {
err := recover()
if err != nil {
const size = 4096
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)] //获得当前goroutine的stacktrace
golog.Error("server", "onConn", "error", 0,
"remoteAddr", c.RemoteAddr().String(),
"stack", string(buf),
)
}
conn.Close()
}()
if allowConnect := conn.IsAllowConnect(); allowConnect == false {
err := mysql.NewError(mysql.ER_ACCESS_DENIED_ERROR, "ip address access denied by kingshard.")
conn.writeError(err)
conn.Close()
return
}
if err := conn.Handshake(); err != nil {
golog.Error("server", "onConn", err.Error(), 0)
c.Close()
return
}
conn.Run()
}
示例3: Accept
func (p *Peer) Accept(conn net.Conn) (_err error) {
defer conn.Close()
p.logFields(SERVE, log.Fields{
"remoteAddr": conn.RemoteAddr(),
}).Debug("accepted connection")
defer func() {
if _err != nil {
p.logErr(SERVE, _err).Error()
}
}()
var failResp string
if p.readAcquire() {
defer p.wg.Done()
} else {
failResp = "sync not available, currently mutating"
}
remoteConfig, err := p.handleConfig(conn, SERVE, failResp)
if err != nil {
return errgo.Mask(err)
}
if failResp == "" {
return p.interactWithClient(conn, remoteConfig, cf.NewBitstring(0))
}
return nil
}
示例4: serve
func (tp *TCPProxy) serve(in net.Conn) {
var (
err error
out net.Conn
)
for i := 0; i < tp.numRemotes(); i++ {
remote := tp.pick()
if !remote.isActive() {
continue
}
// TODO: add timeout
out, err = net.Dial("tcp", remote.addr)
if err == nil {
break
}
remote.inactivate()
plog.Warningf("deactivated endpoint [%s] due to %v for %v", remote.addr, err, tp.MonitorInterval)
}
if out == nil {
in.Close()
return
}
go func() {
io.Copy(in, out)
in.Close()
out.Close()
}()
io.Copy(out, in)
out.Close()
in.Close()
}
示例5: sendSshKeepAlive
// sendSshKeepAlive is a helper which sends a [email protected] request
// on the specified SSH connections and returns true of the request succeeds
// within a specified timeout.
func sendSshKeepAlive(
sshClient *ssh.Client, conn net.Conn, timeout time.Duration) error {
errChannel := make(chan error, 2)
if timeout > 0 {
time.AfterFunc(timeout, func() {
errChannel <- TimeoutError{}
})
}
go func() {
// Random padding to frustrate fingerprinting
_, _, err := sshClient.SendRequest(
"[email protected]", true,
MakeSecureRandomPadding(0, TUNNEL_SSH_KEEP_ALIVE_PAYLOAD_MAX_BYTES))
errChannel <- err
}()
err := <-errChannel
if err != nil {
sshClient.Close()
conn.Close()
}
return ContextError(err)
}
示例6: handleRawConn
// handleRawConn is run in its own goroutine and handles a just-accepted
// connection that has not had any I/O performed on it yet.
func (s *Server) handleRawConn(rawConn net.Conn) {
conn, authInfo, err := s.useTransportAuthenticator(rawConn)
if err != nil {
s.mu.Lock()
s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
s.mu.Unlock()
grpclog.Printf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
rawConn.Close()
return
}
s.mu.Lock()
if s.conns == nil {
s.mu.Unlock()
conn.Close()
return
}
s.mu.Unlock()
if s.opts.useHandlerImpl {
s.serveUsingHandler(conn)
} else {
s.serveNewHTTP2Transport(conn, authInfo)
}
}
示例7: do
func (c *Client) do(method, path string, doOptions doOptions) ([]byte, int, error) {
var params io.Reader
if doOptions.data != nil || doOptions.forceJSON {
buf, err := json.Marshal(doOptions.data)
if err != nil {
return nil, -1, err
}
params = bytes.NewBuffer(buf)
}
if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil {
err := c.checkAPIVersion()
if err != nil {
return nil, -1, err
}
}
req, err := http.NewRequest(method, c.getURL(path), params)
if err != nil {
return nil, -1, err
}
req.Header.Set("User-Agent", userAgent)
if doOptions.data != nil {
req.Header.Set("Content-Type", "application/json")
} else if method == "POST" {
req.Header.Set("Content-Type", "plain/text")
}
var resp *http.Response
protocol := c.endpointURL.Scheme
address := c.endpointURL.Path
if protocol == "unix" {
var dial net.Conn
dial, err = net.Dial(protocol, address)
if err != nil {
return nil, -1, err
}
defer dial.Close()
breader := bufio.NewReader(dial)
err = req.Write(dial)
if err != nil {
return nil, -1, err
}
resp, err = http.ReadResponse(breader, req)
} else {
resp, err = c.HTTPClient.Do(req)
}
if err != nil {
if strings.Contains(err.Error(), "connection refused") {
return nil, -1, ErrConnectionRefused
}
return nil, -1, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, -1, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
return nil, resp.StatusCode, newError(resp.StatusCode, body)
}
return body, resp.StatusCode, nil
}
示例8: handleConnection
//handle read and write
func handleConnection(conn net.Conn) {
//handle read
go func(conn net.Conn) {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print(">>")
line, _, _ := reader.ReadLine()
conn.Write([]byte(line))
}
}(conn)
//handle write
go func(conn net.Conn) {
bs := make([]byte, 1024)
for {
l, err := conn.Read(bs)
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
conn.Close()
}
fmt.Println("<<", string(bs[:l]))
}
}(conn)
}
示例9: handle
func (c *Client) handle(conn net.Conn, ws *WorkServer) {
defer conn.Close()
reader := gob.NewDecoder(conn)
c.ClientInfo = new(Hyades.ClientInfo)
err := reader.Decode(c.ClientInfo)
if err != nil {
c.FrameWorkError(err)
return
}
c.Owner.Stats.Announced(c.ClientInfo)
log.Println(c.ClientInfo.ComputerName, " Connected")
c.Owner.Stats.Connected()
defer c.Owner.Stats.Disconnected(c.ClientInfo)
lc := logicsocket.Wrap(conn)
workConn := lc.NewConnection(WORK)
go c.ServiceWork(workConn)
heartbeatConn := lc.NewConnection(HEARTBEAT)
c.ServiceHeartBeat(heartbeatConn)
}
示例10: ClientHandshake
func (c *tlsCreds) ClientHandshake(addr string, rawConn net.Conn, timeout time.Duration) (_ net.Conn, _ AuthInfo, err error) {
// borrow some code from tls.DialWithDialer
var errChannel chan error
if timeout != 0 {
errChannel = make(chan error, 2)
time.AfterFunc(timeout, func() {
errChannel <- timeoutError{}
})
}
if c.config.ServerName == "" {
colonPos := strings.LastIndex(addr, ":")
if colonPos == -1 {
colonPos = len(addr)
}
c.config.ServerName = addr[:colonPos]
}
conn := tls.Client(rawConn, &c.config)
if timeout == 0 {
err = conn.Handshake()
} else {
go func() {
errChannel <- conn.Handshake()
}()
err = <-errChannel
}
if err != nil {
rawConn.Close()
return nil, nil, err
}
// TODO(zhaoq): Omit the auth info for client now. It is more for
// information than anything else.
return conn, nil, nil
}
示例11: HandleIncomingSSHConn
func HandleIncomingSSHConn(nConn net.Conn, config *ssh.ServerConfig) {
DoneCh := make(chan bool)
go TimeoutConnection(DoneCh, nConn)
_, chans, reqs, err := ssh.NewServerConn(nConn, config)
if err == nil {
DoneCh <- true
}
// Right now that we are out of annoying people land.
defer nConn.Close()
go HandleSSHrequests(reqs)
for newChannel := range chans {
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
log.Printf("WARNING - Rejecting %s Because they asked for a chan type %s that I don't have", nConn.RemoteAddr().String(), newChannel.ChannelType())
continue
}
channel, requests, err := newChannel.Accept()
if err != nil {
log.Printf("WARNING - Was unable to Accept channel with %s", nConn.RemoteAddr().String())
return
}
go HandleSSHrequests(requests)
go ServeDOSTerm(channel)
}
}
示例12: processConnection
func (cons *Socket) processConnection(conn net.Conn) {
cons.AddWorker()
defer cons.WorkerDone()
defer conn.Close()
buffer := shared.NewBufferedReader(socketBufferGrowSize, cons.flags, cons.offset, cons.delimiter)
for cons.IsActive() && !cons.IsFuseBurned() {
conn.SetReadDeadline(time.Now().Add(cons.readTimeout))
err := buffer.ReadAll(conn, cons.Enqueue)
if err == nil {
if err = cons.sendAck(conn, true); err == nil {
continue // ### continue, all is well ###
}
}
// Silently exit on disconnect/close
if !cons.IsActive() || shared.IsDisconnectedError(err) {
return // ### return, connection closed ###
}
// Ignore timeout related errors
if netErr, isNetErr := err.(net.Error); isNetErr && netErr.Timeout() {
continue // ### return, ignore timeouts ###
}
Log.Error.Print("Socket transfer failed: ", err)
cons.sendAck(conn, false)
// Parser errors do not drop the connection
if err != shared.BufferDataInvalid {
return // ### return, close connections ###
}
}
}
示例13: handle
func handle(conn net.Conn) {
defer conn.Close()
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
ln := scanner.Text()
fs := strings.Fields(ln)
// skip blank lines
if len(fs) < 2 {
continue
}
switch fs[0] {
case "GET":
key := fs[1]
value := data[key]
fmt.Fprintf(conn, "%s\n", value)
case "SET":
if len(fs) != 3 {
io.WriteString(conn, "EXPECTED VALUE\n")
continue
}
key := fs[1]
value := fs[2]
data[key] = value
case "DEL":
default:
io.WriteString(conn, "INVALID COMMAND "+fs[0]+"\n")
}
}
}
示例14: handleStatsdTextProtocol
// TODO isn't this identical to handleGraphiteTextProtocol?
func handleStatsdTextProtocol(t *trTransceiver, conn net.Conn, timeout int) {
defer conn.Close() // decrements tcpWg
if timeout != 0 {
conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
}
// We use the Scanner, becase it has a MaxScanTokenSize of 64K
connbuf := bufio.NewScanner(conn)
for connbuf.Scan() {
if stat, err := parseStatsdPacket(connbuf.Text()); err == nil {
t.queueStat(stat)
} else {
log.Printf("parseStatsdPacket(): %v", err)
}
if timeout != 0 {
conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
}
}
if err := connbuf.Err(); err != nil {
log.Println("handleStatsdTextProtocol(): Error reading: %v", err)
}
}
示例15: Receive
// Receive the file in blocks
func Receive(conn net.Conn, filePath string) {
// Defer closing the Connection handle
defer conn.Close()
// Open output file
fout, err := os.Create(filePath)
if err != nil {
log.Println("create ", filePath, "failed...", err)
log.Fatal(err)
}
// Defer closing the output file handle
defer fout.Close()
// File Writer Buffer init.
w := bufio.NewWriter(fout)
inBuffer := make([]byte, blockSize)
for {
numRead, err := conn.Read(inBuffer)
if err != nil || numRead == 0 {
log.Print("Encountered the end of file", numRead, err)
break
}
numWritten, _ := w.Write(inBuffer[:numRead])
log.Println(numRead, "bytes received", numWritten, "bytes written")
w.Flush()
}
}