Python聊天服务器

时间:2015-05-22 17:56:43

标签: python

我是一名基本/新的python程序员。我正在尝试创建一个通过Telnet连接的聊天服务器。我的代码运行良好(我认为),当我尝试通过cmd连接时,它不会让我连接。有没有人知道为什么会出现这个错误,因为它说'连接失败'。顺便说一下,这是我正在使用的代码;

import sys #imports system
import socket #imports socket features
from _thread import  *

host = '' #sets host to your IP 
port = 5555 #Connects to any port
s =socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try: #runs the connection
    s.bind((host, port))
except socket.error as e:
    print(str(e))

s.listen(5) #listens for a queue of 5
print ('Waiting for a connection...')
def threaded_client(conn): #each time someone makes a connection it will pass them through a threaded client
    conn.send(str.encode('Welcome, type your info\n'))

    while True: #giving a server output to all users
        data =conn.recv(2048)
        reply = 'Server Output: '+data.decode(uft-8)
        if not data:
            break
        conn.sendall(str.encode(reply))
    conn.close()

while True:

    conn, addr = s.accept() #connecting to address and accepts
    print ('Connected to: '+addr[0]+':'+str(addr[1])) #just some additional information that the user will see.

    start_new_thread(threaded_client,(conn,))

1 个答案:

答案 0 :(得分:0)

您是尝试从本地网络还是通过远程连接? 如果您尝试从远程计算机进行连接,则应将端口5555端口转发,路由器可能会阻止您的连接。