为什么客户端和服务器在同一进程时会连接被拒绝?
我在同一个程序里运行客户端和服务器时遇到了问题。每次我尝试让客户端连接服务器时,都会出现这个错误:
Traceback (most recent call last):
File "dirWatch.py", line 78, in <module>
startDirWatch(sLink)
File "dirWatch.py", line 68, in startDirWatch
sC.client('/home/homer/Downloads/test.txt')
File "/home/homer/Desktop/CSC400/gsync/serverClient.py", line 15, in client
sock.connect((host,port))
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused
这是我用的代码,我基本上是在尝试做一个文件同步程序。我是新来的,所以如果我没有提供更多细节,请多多包涵。以下是我测试客户端和服务器代码的部分:
thread.start_new_thread(sC.server ,('localhost', 50001))
sC.client('/home/homer/Downloads/test.txt')
这是客户端和服务器的实际代码,挺简单的,我只是想让它们连接起来:
def client(filename, host = defaultHost, port = defaultPort):
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host,port))
sock.send((filename + '\n').encode())
sock.close()
def serverthread(clientsock):
sockfile = clientsock.makefile('r')
filename = sockfile.readline()[:-1]
try:
print filename
except:
print('Error recieving or writing: ', filename)
clientsock.close()
def server(host, port):
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind((host,port))
serversock.listen(5)
while True:
clientsock, clientaddr = serversock.accept()
print('Connection made');
thread.start_new_thread(serverthread, (clientsock,))
任何帮助或建议都会很感激。谢谢你的阅读。
2 个回答
1
与其去处理线程同步和底层套接字的一些麻烦(比如说,socket.send
可能不会把你传入的整个字符串都发送出去!),不如试试 Twisted 吧!
下面是一个使用 Twisted 的示例版本,完全没有同步问题:
from twisted.internet import reactor
from twisted.internet.protocol import ServerFactory, ClientFactory
from twisted.protocols.basic import LineOnlyReceiver
class FileSyncServer(LineOnlyReceiver):
def lineReceived(self, line):
print "Received a line:", repr(line)
self.transport.loseConnection()
class FileSyncClient(LineOnlyReceiver):
def connectionMade(self):
self.sendLine(self.factory.filename)
self.transport.loseConnection()
def server(host, port):
factory = ServerFactory()
factory.protocol = FileSyncServer
reactor.listenTCP(port, factory, interface=host)
def client(filename, host, port):
factory = ClientFactory()
factory.protocol = FileSyncClient
factory.filename = filename
reactor.connectTCP(host, port, factory)
server("localhost", 50001)
client("test.txt", "localhost", 50001)
reactor.run()
1
我首先想到的可能是,当客户端尝试连接时,服务器的线程还没有真正启动;客户端在连接,但没有任何东西在监听。创建一个线程并把控制权交给它需要一些时间。你可以在客户端连接之前让它“休息”一下,或者尝试连接几次,或者更高级一点,让服务器线程在套接字打开时发个信号。