2017-06-30 73 views
0

我使用python創建了一個小型局域網聊天,並且出於某種原因,我一直拒絕我的連接。以下是錯誤:Python - 連接不斷被拒絕

File "client.py", line 35, in data, addr = s.recvfrom(1024) ConnectionRefusedError: [Errno 111] Connection refused

這裏是server.py代碼:

import socket 
from time import sleep 

host = '127.0.0.1' 
port = 5000 
ips = [] 

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
s.bind((host, port)) 

print('server started') 

quitS = False 
while not quitS: 
    data, addr = s.recvfrom(1024) 
    if 'quitS' in str(data): 
     print('server will close in...') 
     for i in reversed(range(4)): 
      sleep(1) 
      print (i) 
     quitS = True 
     break 
    print (str(addr) + ': '+str(data)) 
    if addr not in ips: 
     ips.append(addr) 
    for ip in ips: 
     s.sendto(data, ip) 

s.close() 

而且我client.py:

import socket 
from time import sleep 
from getpass import getpass 

host = '192.168.1.126' 
port = 5000 

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
s.connect((host, port)) 

loop = True 
while loop: 
    try: 
     s.settimeout(4) 
     text = input('Type: ') 
     data = text.encode('UTF-8') 
     if text == 'quitS': 
      passwd = False 
      pcount = 0 
      while not passwd: 
       pcount += 1 
       pwd = getpass() 
       if pwd == '1234': 
        s.send(data) 
        passwd = True 
       elif pcount == 3: 
        print ('HHell no, go away') 
        break 
     elif text == 'q': 
      s.close() 
      break 
     elif text == '': 
      print('Inavalid, entry not allowed.') 
     else: 
      s.send(data) 
      data, addr = s.recvfrom(1024) 
      print (str(addr) + ': ' + str(data)) 
    except (socket.timeout, ConnectionResetError): 
     loop = False 
     sleep(2) 
     print('Server is dead, will close in...') 
     for i in reversed(range(4)): 
      sleep(1) 
      print (i) 

的server.py是我的RPI運行,他是我的ufw status verbose輸出:

5000      ALLOW IN Anywhere 
6001      ALLOW IN Anywhere 
5001      ALLOW IN Anywhere 
22       ALLOW IN Anywhere 
5900      ALLOW IN Anywhere 
5800      ALLOW IN Anywhere 
5000      ALLOW IN Anywhere (v6) 
6001      ALLOW IN Anywhere (v6) 
5001      ALLOW IN Anywhere (v6) 
22       ALLOW IN Anywhere (v6) 
5900      ALLOW IN Anywhere (v6) 
5800      ALLOW IN Anywhere (v6) 

5000      ALLOW OUT Anywhere 
5000      ALLOW OUT Anywhere (v6) 

client.py ufw設置幾乎相同,我允許在端口5000上進出。

我在做什麼錯?並且,如果您對代碼有任何建議,請告訴我!

+0

像@DeepSpace提到的那樣,主機和客戶端IP在這裏很重要。如果您沒有從同一臺機器連接/測試,請不要綁定到本地主機。 – Peri461

+0

所以當127.0.0.1打開時,它只會讓他自己的連接? @DeepSpace – DiogoF

+0

@DiogoF是的,請參閱我的回答以及我鏈接的問題。 – DeepSpace

回答