Socket not visible using Python on Ubuntu Server
I'm writing an application that is supposed to listen for a client, and when it connects, it should grab some data. It works fine when I run it locally on either my own computer, or the server, but when I try and run it on the server, and connect from my computer, it doesn't work at all. The connection times out.
I've tried running the program, and then checking netstat (on the server), and it only shows anything if I have my host set to localhost. If I set my host to the server's IP address (or hostname, or socket.getfqdn()
), then nothing shows up in netstat.
The code is as follows:
class Listen(threading.Thread):
def __init__(self):
self.PORT = 2079
self.HOST = socket.getfqdn()
threading.Thread.__init__(self)
self.finished = threading.Event()
def stop(self):
self.finished.set()
self.join()
def run(self):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((self.HOST, self.PORT))
server.listen(5)
while not self.finished.isSet():
try:
server.settimeout(1)
channel, details = server.accept()
server.settimeout(None)
Client(channel, details).start()
except socket.timeout:
pass
class Client(threading.Thread):
def __init__(self, channel, details):
self.channel = channel
self.details = details
self.log = []
threading.Thread.__init__(self)
def run(self):
print 'Received connection:', self.details [ 0 ]
entries = int(self.channel.recv(3))
print "Receiving", entries, "new entries"
for i in range(entries):
self.log.append([])
self.log[i].append(float(self.channel.recv(10)))
self.log[i].append(float(self.channel.recv(10)))
self.log[i].append(self.channel.recv(14))
self.channel.close()
print 'Closed connection:', self.details [ 0 ]
print "The obtained log: "
print self.log
def main():
listen 开发者_StackOverflow= Listen()
listen.start()
while True:
input = raw_input(">>").lower()
if input in ["start"]:
if listen.isAlive():
print "Already started"
else:
listen = Listen()
listen.start()
if input in ["stop"]:
if not listen.isAlive():
print "Already stopped"
else:
listen.stop()
if input in ["exit"]:
if listen.isAlive():
listen.stop()
sys.exit()
if input in ["status"]:
print "The server is " + ["not ", ""][listen.isAlive()] + "running"
if __name__ == '__main__':
main()
Instead of server.bind((self.HOST, self.PORT))
, try:
server.bind(('', self.PORT))
For IPv4 addresses the empty string represents INADDR_ANY; when receiving a socket bound to this address, your process will receive packets from all interfaces (not just the loop-back or the primary Ethernet interface).
精彩评论