我运行以下脚本:
import socket, threading, time,Queue
if __name__ == '__main__':
pass
print("Starting...")
def server():
s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print("Connection accepted from " + repr(addr[1]))
c.send("Server approved connection\n")
print (addr[1]) + ": " + c.recv(1026)
c.close()
def client ():
time.sleep(5)
print("Client Started")
s = socket.socket()
host = socket.gethostname()
port = 1247
s.connect((host, port))
print (s.recv(1024))
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print ("the message has been sent")
q = Queue.Queue()
t = threading.Thread(client(), args = (q))
t.daemon = True
t.start()
server()
我收到此错误:
Starting...
Client Started
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
请注意,端口1247已在我的设备(Ubuntu OS)中打开。
拒绝连接意味着无法连接。但是服务器有什么问题,我找不到它的问题。经过一周的尝试,非常感谢任何帮助!
答案 0 :(得分:1)
创建线程时,您不小心启动了客户端。 threading.Thread
的第一个参数是client()
,它执行包含初始sleep
的客户端。哪个阻止主线程。你应该把它改成
t = threading.Thread(target=client, args = (q,))
target参数需要一个可调用对象,即您的客户端。一旦开始,它将在不同的线程上执行客户端。请注意,()
之后缺少client
。