在Windows中运行Python聊天客户端脚本

时间:2017-05-07 12:32:34

标签: python linux sockets python-sockets

我制作了一个聊天服务器和聊天客户端python脚本,服务器在一个端口上运行,尽可能多的客户端可以像irc聊天室一样连接和聊天,在linux上工作正常,但不在Windows上运行

这是聊天客户端代码

import sys
import socket
import select

def chat_client():
    if(len(sys.argv) < 3) :
        print 'Usage : python chat_client.py hostname port'
        sys.exit()

    host = sys.argv[1]
    port = int(sys.argv[2])

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)

    # connect to remote host
    try :
        s.connect((host, port))
    except :
        print 'Unable to connect'
        sys.exit()

    print 'Connected to remote host. You can start sending messages'
    sys.stdout.write('[Me] '); sys.stdout.flush()

    while 1:
        socket_list = [sys.stdin, s]

        # Get the list sockets which are readable
        ready_to_read,ready_to_write,in_error = select.select(socket_list , [], [])

        for sock in ready_to_read:             
            if sock == s:
                # incoming message from remote server, s
                data = sock.recv(4096)
                if not data :
                    print '\nDisconnected from chat server'
                    sys.exit()
                else :
                    #print data
                    sys.stdout.write(data)
                    sys.stdout.write('[Me] '); sys.stdout.flush()     

            else :
                # user entered a message
                msg = sys.stdin.readline()
                s.send(msg)
                sys.stdout.write('[Me] '); sys.stdout.flush() 

if __name__ == "__main__":

    sys.exit(chat_client())

问题在于windows不像linux那样查看文件的套接字,所以select函数不起作用(我认为)

问题从这一行开始

ready_to_read,ready_to_write,in_error = select.select(socket_list , [], [])

我可以将此脚本移植到Windows吗?

0 个答案:

没有答案