程序python套接字

我在这个 Python 代码中有一个问题。请帮我。谢谢


import sys

import socket

import select


HOST = 'sys.ase.ro'

SOCKET_LIST = []

RECV_BUFFER = 4096

PORT = 6508



def chat_server():

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    server_socket.bind((HOST, PORT))

    server_socket.listen(10)


    SOCKET_LIST.append(server_socket)


    print "Chat server started on port " + str(PORT)


    while 1:



        ready_to_read, ready_to_write, in_error = select.select(SOCKET_LIST, [], [], 0)


        for sock in ready_to_read:


            if sock == server_socket:


                sockfd, addr = server_socket.accept()


                SOCKET_LIST.append(sockfd)

                print "Client (%s, %s) connected" % addr


                broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)



            else:


                try:


                    data = sock.recv(RECV_BUFFER)

                    if data:


                        broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)

                    else:


                        if sock in SOCKET_LIST:

                            SOCKET_LIST.remove(sock)



                        broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)



                except:

                    broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)

                    continue


    server_socket.close()



# broadcast chat messages to all connected clients

def broadcast(server_socket, sock, message):

    for socket in SOCKET_LIST:


        if socket != server_socket and socket != sock:

            try:

                socket.send(message)

            except:


                socket.close()


                if socket in SOCKET_LIST:

                    SOCKET_LIST.remove(socket)



if __name__ == "__main__":

    sys.exit()

慕侠2389804
浏览 150回答 2
2回答

紫衣仙女

我找到了为什么它不起作用我的代码失败的原因是因为我试图绑定到外部主机名。我的机器不知道这个主机名,因此出现错误消息。我在 localhost 中更改它并且它有效。

MMMHUHU

您正在尝试将套接字绑定到远程地址。从Windows 文档:bind 函数将本地地址与套接字相关联。改用连接:server_socket.connect((HOST, PORT))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python