I'm new to python :) I would like to create persistent socket. I tried to do this using file descriptors. What I tried is:
Open a socket socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Get it's file descriptor number
fd = s.fileno()
Open the file descriptor as I/O
os.open(fd)
But I get OSError: [Errno 9] Bad file descriptor
I said I'm new to python and maybe I'm wrong with the implementation. But I tried a simpler example os.close(s.fileno())
and I get the same error OSError: [Errno 9] Bad file descriptor
I found an example written in ruby and I tested it, it works. How do I make persistent network sockets on Unix in Ruby?
Can any one write this into python for me, what I want to achieve is: socket_start.py google.com (thie will print the fd number) sleep 10 soc开发者_C百科ket_write.py fd_number 'something' sleep 10 socket_read.py fd_number 1024
I hope you understand what I want to do. Thanks in advice!
After your responses I tried next code:
1
#!/usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('google.com', 80))
s.send('GET /\n')
print s.fileno()
2
#!/usr/bin/python
import os
import sys
fd = int(sys.argv[1])
os.read(fd, 1024)
And the error is OSError: [Errno 9] Bad file descriptor
I'm sure what the problem is (I'm a php developer). I think same as php, python deletes garbage after closing a script. How to solve this in python ?
You use os.fdopen() to open file descriptors.
I'm actually surprised that you got that far because os.open
requires a filename and flags stating which mode to open the file in. for example fd = os.open('foo.txt', os.O_RONLY)
. As my example indicates, it returns a file descriptor rather than accepting one.
If you want to re-create the socket by a parameter received on the commandline (i.e., the socket), use socket.fromfd
精彩评论