我正在閱讀有關套接字,發現一個很好的練習來嘗試:一個簡單的聊天服務器,迴應輸入。這似乎是一個常見的練習,我發現了幾個例子,如chatserver5.py和一些SO問題。問題是我只能使用telnet localhost 51234
而不是telnet 192.168.1.3 51234
(其中192.168.1.3是我的「服務器」的網絡IP)連接。不用說,我無法從我的網絡上的其他機器連接。我得到以下輸出:Python中的簡單遠程登錄聊天服務器
Trying 192.168.1.3...
telnet: connect to address 192.168.1.3: Connection refused
telnet: Unable to connect to remote host
這裏是我的代碼:
import socket, threading
HOST = '127.0.0.1'
PORT = 51234
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)
clients = [] #list of clients connected
lock = threading.Lock()
class chatServer(threading.Thread):
def __init__(self, (socket,address)):
threading.Thread.__init__(self)
self.socket = socket
self.address= address
def run(self):
lock.acquire()
clients.append(self)
lock.release()
print '%s:%s connected.' % self.address
while True:
data = self.socket.recv(1024)
if not data:
break
for c in clients:
c.socket.send(data)
self.socket.close()
print '%s:%s disconnected.' % self.address
lock.acquire()
clients.remove(self)
lock.release()
while True: # wait for socket to connect
# send socket to chatserver and start monitoring
chatServer(s.accept()).start()
我有telnet或插座沒有經驗。爲什麼我無法遠程連接,我該如何解決這個問題?
你有防火牆嗎? –