本文整理汇总了Golang中net.FileConn函数的典型用法代码示例。如果您正苦于以下问题:Golang FileConn函数的具体用法?Golang FileConn怎么用?Golang FileConn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了FileConn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: newFakeVTYServer
func newFakeVTYServer() (*fakeVTYServer, error) {
fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0)
if err != nil {
return nil, err
}
vtyClientFile := os.NewFile(uintptr(fds[1]), "vty-client")
vtyClientConn, err := net.FileConn(vtyClientFile)
if err != nil {
return nil, err
}
vtyServerFile := os.NewFile(uintptr(fds[0]), "vty-server")
vtyServerConn, err := net.FileConn(vtyServerFile)
if err != nil {
return nil, err
}
syscall.SetNonblock(fds[0], false)
vs := &fakeVTYServer{
clientConn: vtyClientConn,
serverConn: vtyServerConn,
clientFile: vtyClientFile,
serverFile: vtyServerFile,
send: make(chan []byte),
received: make(chan []byte),
}
go vs.read()
go vs.write()
return vs, nil
}
示例2: TfoDial
// dial tcp with tcp fastopen
// 第一个包体积不要太大,需要小于一定数量,否则会被吃掉(正确性问题),
// 如果过大,此处会在连接时发送前一部分,连接后又发送一部分
func TfoDial(nextAddr string, data []byte) (conn net.Conn, err error) {
s, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM, 0)
if err != nil {
return nil, err
}
defer unix.Close(s)
sa, err := kmgUnix.IPv4TcpAddrToUnixSocksAddr(nextAddr)
if err != nil {
return nil, err
}
if len(data) <= tfoFirstSize {
err = unix.Sendto(s, data, unix.MSG_FASTOPEN, sa)
if err != nil {
return
}
} else {
err = unix.Sendto(s, data[:tfoFirstSize], unix.MSG_FASTOPEN, sa)
if err != nil {
return
}
}
f := os.NewFile(uintptr(s), "TFODial")
defer f.Close()
conn, err = net.FileConn(f)
if err != nil {
return
}
if len(data) > tfoFirstSize {
_, err = conn.Write(data[tfoFirstSize:])
if err != nil {
return nil, err
}
}
return conn, nil
}
示例3: Start
func (g *statsdUdpTextServiceManager) Start(file *os.File) error {
var (
err error
udpAddr *net.UDPAddr
)
if config.StatsdUdpListenSpec != "" {
if file != nil {
g.conn, err = net.FileConn(file)
} else {
udpAddr, err = net.ResolveUDPAddr("udp", config.StatsdUdpListenSpec)
if err == nil {
g.conn, err = net.ListenUDP("udp", udpAddr)
}
}
} else {
log.Printf("Not starting Statsd UDP protocol because statsd-udp-listen-spec is blank.")
return nil
}
if err != nil {
return fmt.Errorf("Error starting Statsd UDP Text Protocol serviceManager: %v", err)
}
fmt.Printf("Statsd UDP protocol Listening on %s\n", config.StatsdTextListenSpec)
// for UDP timeout must be 0
go handleStatsdTextProtocol(g.t, g.conn, 0)
return nil
}
示例4: Connect
func (o *Object) Connect() (net.Conn, error) {
ret, err := o.Send(&Message{Verb: Connect, Ret: RetPipe})
if err != nil {
return nil, err
}
// FIXME: set Att
msg, err := ret.Receive(0)
if err == io.EOF {
return nil, fmt.Errorf("unexpected EOF")
}
if msg.Verb == Connect {
if msg.Att == nil {
return nil, fmt.Errorf("missing attachment")
}
conn, err := net.FileConn(msg.Att)
if err != nil {
msg.Att.Close()
return nil, err
}
msg.Att.Close()
return conn, nil
}
if msg.Verb == Error {
return nil, fmt.Errorf(strings.Join(msg.Args[:1], ""))
}
return nil, fmt.Errorf("unexpected verb %v", msg.Verb)
}
示例5: NewUdpGobInput
func NewUdpGobInput(addrStr string, fd *uintptr) *UdpGobInput {
var listener net.Conn
if *fd != 0 {
udpFile := os.NewFile(*fd, "udpFile")
fdConn, err := net.FileConn(udpFile)
if err != nil {
log.Printf("Error accessing UDP fd: %s\n", err.Error())
return nil
}
listener = fdConn
} else {
udpAddr, err := net.ResolveUDPAddr("udp", addrStr)
if err != nil {
log.Printf("ResolveUDPAddr failed: %s\n", err.Error())
return nil
}
listener, err = net.ListenUDP("udp", udpAddr)
if err != nil {
log.Printf("ListenUDP failed: %s\n", err.Error())
return nil
}
}
decoder := gob.NewDecoder(listener)
return &UdpGobInput{listener: &listener, decoder: decoder}
}
示例6: Init
func (self *UdpInput) Init(config interface{}) error {
self.config = config.(*UdpInputConfig)
if len(self.config.Address) > 3 && self.config.Address[:3] == "fd:" {
// File descriptor
fdStr := self.config.Address[3:]
fdInt, err := strconv.ParseUint(fdStr, 0, 0)
if err != nil {
log.Println(err)
return fmt.Errorf("Invalid file descriptor: %s", self.config.Address)
}
fd := uintptr(fdInt)
udpFile := os.NewFile(fd, "udpFile")
self.listener, err = net.FileConn(udpFile)
if err != nil {
return fmt.Errorf("Error accessing UDP fd: %s\n", err.Error())
}
} else {
// IP address
udpAddr, err := net.ResolveUDPAddr("udp", self.config.Address)
if err != nil {
return fmt.Errorf("ResolveUDPAddr failed: %s\n", err.Error())
}
self.listener, err = net.ListenUDP("udp", udpAddr)
if err != nil {
return fmt.Errorf("ListenUDP failed: %s\n", err.Error())
}
}
return nil
}
示例7: LessDelayTcpConn
func LessDelayTcpConn(conn *net.TCPConn) (connOut net.Conn, err error) {
//err = conn.SetKeepAlive(true)
//if err!=nil{
// kmgErr.LogErrorWithStack(err)
// return nil,err
//}
//err = conn.SetKeepAlivePeriod(5*time.Second) //5s太小,耗流量非常凶残.
//if err!=nil{
// kmgErr.LogErrorWithStack(err)
// return nil,err
//}
fd, err := conn.File()
if err != nil {
kmgErr.LogErrorWithStack(err)
return
}
conn1, err := net.FileConn(fd)
if err != nil {
fd.Close()
kmgErr.LogErrorWithStack(err)
return
}
conn.Close()
//尝试将连接重新设置回 block 模式,减少cpu占用,此方案不稳定,并且不知道如何解决不稳定的问题.
//err = unix.SetNonblock(int(fd.Fd()),true)
//if err!=nil{
// fd.Close()
// kmgErr.LogErrorWithStack(err)
// return nil,err
//}
//return NewDebugConn(fasterTcpConn{TCPConn: conn, fd: fd},conn.LocalAddr().String()+"_"+conn.RemoteAddr().String()), nil
return &fasterTcpConn{TCPConn: conn1.(*net.TCPConn), fd: fd}, nil
}
示例8: Start
func (g *graphiteUdpTextServiceManager) Start(file *os.File) error {
var (
err error
udpAddr *net.UDPAddr
)
if g.listenSpec != "" {
if file != nil {
g.conn, err = net.FileConn(file)
} else {
udpAddr, err = net.ResolveUDPAddr("udp", processListenSpec(g.listenSpec))
if err == nil {
g.conn, err = net.ListenUDP("udp", udpAddr)
}
}
} else {
log.Printf("Not starting Graphite UDP protocol because graphite-udp-listen-spec is blank.")
return nil
}
if err != nil {
return fmt.Errorf("Error starting Graphite UDP Text Protocol serviceManager: %v", err)
}
fmt.Printf("Graphite UDP protocol Listening on %s\n", processListenSpec(g.listenSpec))
// for UDP timeout must be 0
go handleGraphiteTextProtocol(g.rcvr, g.conn, 0)
return nil
}
示例9: HijackSession
// Attempt to hijack session previously running bot
func (irc *IrcCon) HijackSession() bool {
unaddr, err := net.ResolveUnixAddr("unix", irc.unixastr)
if err != nil {
irc.Log(LWarning, "could not resolve unix socket")
return false
}
con, err := net.DialUnix("unix", nil, unaddr)
if err != nil {
fmt.Println("Couldnt restablish connection, no prior bot.")
fmt.Println(err)
return false
}
ncon, err := sendfd.RecvFD(con)
if err != nil {
panic(err)
}
netcon, err := net.FileConn(ncon)
if err != nil {
panic(err)
}
irc.reconnect = true
irc.con = netcon
return true
}
示例10: createAttachment
func createAttachment(stream *spdystream.Stream) (*os.File, error) {
if stream.IsFinished() {
return nil, fmt.Errorf("stream already finished")
}
socketFds, socketErr := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM|syscall.FD_CLOEXEC, 0)
if socketErr != nil {
return nil, socketErr
}
pipe := os.NewFile(uintptr(socketFds[1]), "")
defer pipe.Close()
conn, connErr := net.FileConn(pipe)
if connErr != nil {
return nil, connErr
}
go func() {
io.Copy(conn, stream)
conn.Close()
}()
go func() {
io.Copy(stream, conn)
}()
return os.NewFile(uintptr(socketFds[0]), ""), nil
}
示例11: mount
func mount(dir string, ready chan<- struct{}, errp *error) (fusefd *os.File, err error) {
// linux mount is never delayed
close(ready)
fds, err := syscall.Socketpair(syscall.AF_FILE, syscall.SOCK_STREAM, 0)
if err != nil {
return nil, fmt.Errorf("socketpair error: %v", err)
}
defer syscall.Close(fds[0])
defer syscall.Close(fds[1])
cmd := exec.Command("fusermount", "--", dir)
cmd.Env = append(os.Environ(), "_FUSE_COMMFD=3")
writeFile := os.NewFile(uintptr(fds[0]), "fusermount-child-writes")
defer writeFile.Close()
cmd.ExtraFiles = []*os.File{writeFile}
out, err := cmd.CombinedOutput()
if len(out) > 0 || err != nil {
return nil, fmt.Errorf("fusermount: %q, %v", out, err)
}
readFile := os.NewFile(uintptr(fds[1]), "fusermount-parent-reads")
defer readFile.Close()
c, err := net.FileConn(readFile)
if err != nil {
return nil, fmt.Errorf("FileConn from fusermount socket: %v", err)
}
defer c.Close()
uc, ok := c.(*net.UnixConn)
if !ok {
return nil, fmt.Errorf("unexpected FileConn type; expected UnixConn, got %T", c)
}
buf := make([]byte, 32) // expect 1 byte
oob := make([]byte, 32) // expect 24 bytes
_, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
scms, err := syscall.ParseSocketControlMessage(oob[:oobn])
if err != nil {
return nil, fmt.Errorf("ParseSocketControlMessage: %v", err)
}
if len(scms) != 1 {
return nil, fmt.Errorf("expected 1 SocketControlMessage; got scms = %#v", scms)
}
scm := scms[0]
gotFds, err := syscall.ParseUnixRights(&scm)
if err != nil {
return nil, fmt.Errorf("syscall.ParseUnixRights: %v", err)
}
if len(gotFds) != 1 {
return nil, fmt.Errorf("wanted 1 fd; got %#v", gotFds)
}
f := os.NewFile(uintptr(gotFds[0]), "/dev/fuse")
return f, nil
}
示例12: getConn
// getConn checks if the file descriptor at the given offset is a socket and
// returns a net.Conn bound to this file descriptor.
func getConn(num int) (conn net.Conn, err error) {
fd := listenFdsStart + num
f := osm.NewFile(uintptr(fd), "")
conn, err = net.FileConn(f)
f.Close()
return conn, err
}
示例13: Accept
func (tl *TCPListener) Accept() (fd int, conn net.Conn, err error) {
cpointer, err := tl.Listener.AcceptTCP()
if err != nil {
return
}
file, err := cpointer.File()
fd = int(file.Fd())
conn, err = net.FileConn(file)
return
}
示例14: followLogs
func (c *Container) followLogs(log log15.Logger, buffer host.LogBuffer) error {
c.l.logStreamMtx.Lock()
defer c.l.logStreamMtx.Unlock()
if _, ok := c.l.logStreams[c.job.ID]; ok {
return nil
}
log.Info("getting stdout")
stdout, stderr, initLog, err := c.Client.GetStreams()
if err != nil {
log.Error("error getting streams", "err", err)
return err
}
nonblocking := func(file *os.File) (net.Conn, error) {
// convert to a net.Conn so we do non-blocking I/O on the fd and Close
// will make calls to Read return straight away (using read(2) would
// not have this same behaviour, meaning we could potentially read
// from the stream after we have closed and returned the buffer).
defer file.Close()
return net.FileConn(file)
}
muxConfig := logmux.Config{
AppID: c.job.Metadata["flynn-controller.app"],
HostID: c.l.state.id,
JobType: c.job.Metadata["flynn-controller.type"],
JobID: c.job.ID,
}
logStreams := make(map[string]*logmux.LogStream, 3)
stdoutR, err := nonblocking(stdout)
if err != nil {
log.Error("error streaming stdout", "err", err)
return err
}
logStreams["stdout"] = c.l.mux.Follow(stdoutR, buffer["stdout"], 1, muxConfig)
stderrR, err := nonblocking(stderr)
if err != nil {
log.Error("error streaming stderr", "err", err)
return err
}
logStreams["stderr"] = c.l.mux.Follow(stderrR, buffer["stderr"], 2, muxConfig)
initLogR, err := nonblocking(initLog)
if err != nil {
log.Error("error streaming initial log", "err", err)
return err
}
logStreams["initLog"] = c.l.mux.Follow(initLogR, buffer["initLog"], 3, muxConfig)
c.l.logStreams[c.job.ID] = logStreams
return nil
}
示例15: Listen
//Listen advertises a single protocol, proto, in the directory the server
//was created with. It will invoke handler in a new goroutine every time
//a fd representing a tcp socket is sent down the unix domain socket
//created at dir/proto by an instance of etnsrv on dir.
//
//Warning: if there is an existing file named dir/proto it will be deleted.
//
//It is safe to call multiple times on same server, with different proto.
func (s *Server) Listen(proto string, handler func(*net.TCPConn) error) error {
if len(proto) > 255 {
return etsn.ErrProtocolIdentifierTooLong
}
nm := filepath.Join(s.dir, proto)
if err := os.Remove(nm); err != nil {
pe := err.(*os.PathError)
if pe.Err.Error() != "no such file or directory" {
return err
}
}
c, err := net.Listen("unix", nm)
if err != nil {
return err
}
ul := c.(*net.UnixListener)
for {
conn, err := ul.AcceptUnix()
if err != nil {
//BUG(jmf) There are surely many an error that should lead to
//us breaking out of the listen loop. For example if another
//process deletes our socket
s.log(err)
continue
}
fs, err := fd.Get(conn, 1, nil)
if err != nil {
s.log(err)
continue
}
if len(fs) != 1 {
s.log(errors.New("Did not receive exactly one fd"))
continue
}
f := fs[0]
ic, err := net.FileConn(f)
if err != nil {
f.Close()
s.log(err)
continue
}
s.log(f.Close())
tcp, ok := ic.(*net.TCPConn)
if !ok {
s.log(errors.New("Received invalid socket type"))
ic.Close()
continue
}
go s.log(handler(tcp))
}
}