0
ENV:LINUX + python3 + rornadoPython的套接字:socket連接被拒絕
當我運行client.py,他建議我的連接被拒絕,幾個端口,使用127.0.0.1:7233,The服務器沒有任何迴應,但客戶端提示拒絕連接,誰能告訴我爲什麼?
server.py
# coding:utf8
import socket
import time
import threading
# accept conn
def get_hart(host, port):
global clien_list
print('begin get_hart')
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
print(clien_list)
while True:
try:
clien, address = s.accept()
try:
clien_data = clien.recv(1024).decode('utf8')
if clien_data == str(0):
clien_id = clien_reg()
clien.send(str(clien_id))
print(clien_list)
else:
clien_list[int(clien_data)]['time'] = time.time()
# print clien_data
except:
print('send fail!')
clien.close()
except:
print("accept fail!")
continue
# client reg
def clien_reg():
global clien_list
tim = str(time.time()/100).split('.')
id = int(tim[1])
clien_list[id] = {"time": time.time(), "state": 0}
return id
# client dict
def check_hart(clien_list, delay, lost_time):
while True:
for id in clien_list:
if abs(clien_list[id]['time'] - time.time()) > lost_time:
clien_list[id]['state'] = 0
del clien_list[id] # del offline client
break # err
else:
clien_list[id]['state'] = 1
print(clien_list)
time.sleep(delay)
if __name__ == '__main__':
host = '127.0.0.1'
port = 7233
global clien_list # Dict: client info
clien_list = {}
lost_time = 30 # timeout
print('begin threading')
try:
threading.Thread(target=get_hart,args=(host,port,),name='getHart')
threading.Thread(target=check_hart,args=(clien_list, 5, lost_time,))
except Exception as e:
print("thread error!"+e)
while 1:
pass
print('e')
client.py
# coding:utf8
import socket
import time
# sent pkg
def send_hart(host, port, delay):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print(host,port)
global clien_id
try:
s.connect((host, port))
s.send(clien_id)
if clien_id == 0:
try:
to_clien_id = s.recv(1024)
clien_id = to_clien_id
except:
print('send fail!')
print(to_clien_id) # test id
time.sleep(delay)
except Exception as e:
print('connect fail!:'+e)
time.sleep(delay)
if __name__ == '__main__':
host = '127.0.0.1'
port = 7233
global clien_id
clien_id = 0 # client reg id
while True:
send_hart(host, port, 5)
錯誤
Traceback (most recent call last):
File "/home/ubuntu/XPlan/socket_test/client.py", line 13, in send_hart
s.connect((host, port))
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/ubuntu/XPlan/socket_test/client.py", line 34, in <module>
send_hart(host, port, 5)
File "/home/ubuntu/XPlan/socket_test/client.py", line 24, in send_hart
print('connect fail!:'+e)
TypeError: Can't convert 'ConnectionRefusedError' object to str implicitly
Process finished with exit code 1