I have this python code that works only when the TCP_IP is localhost. If I change it to some other server IP for e.g. 23.21.167.61 then it fails to send the file even if the other server is listening.
import socket
from threading import Thread
from SocketServer import ThreadingMixIn
TCP_IP = 'localhost'
TCP_PORT = 9001
BUFFER_SIZE = 1024
class ClientThread(Thread):
def __init__(self,ip,port,sock):
Thread.__init__(self)
self.ip = ip
self.port = port
self.sock = sock
print " New thread started for "+ip+":"+str(port)
def run(self):
filename='mytext.txt'
f = open(filename,'rb')
while True:
l = f.read(BUFFER_SIZE)
while (l):
self.sock.send(l)
#print('Sent ',repr(l))
l = f.read(BUFFER_SIZE)
if not l:
f.close()
self.sock.close()
break
tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
while True:
tcpsock.listen(5)
print "Waiting for incoming connections..."
(conn, (ip,port)) = tcpsock.accept()
print 'Got connection from ', (ip,port)
newthread = ClientThread(ip,port,conn)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
I get an error while binding to IP. I can use connect method but then I will not be able to take advantage of threading as explained here... http://www.bogotobogo.com/python/python_network_programming_server_client_file_transfer.php
[root@ip-10-93-136-166 ec2-user]# python server2.py
Traceback (most recent call last):
File "server2.py", line 34, in <module>
tcpsock.bind((TCP_IP, TCP_PORT))
File "/usr/lib64/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 99] Cannot assign requested address
答案 0 :(得分:0)
当我使用像''而不是localhost
这样的空字符串时,这很有效TCP_IP = ''
然后从客户端我连接并从远程服务器23.21.167.61接收文件 我不确定空字符串是什么意思。但它解决了这个问题。