我如何使用这两个Python聊天室代码(服务器和客户端)在不同的计算机之间进行通信?

时间:2015-01-04 09:57:17

标签: python chat server tcp-ip

我一直在寻找一个冬季假期的项目,并为Python聊天室找到了一些人的代码。

我既有服务器脚本,也有客户端脚本。但是,只有当他们在同一台计算机上时,我才能使它工作。我已尝试将客户端放在另一台计算机上,但我似乎无法使其运行(它表示无法连接)。

这是服务器代码:

# Tcp Chat server
import socket, select

#Function to broadcast chat messages to all connected clients
def broadcast_data (sock, message):
    #Do not send the message to master socket and the client who has send us the message
    for socket in CONNECTION_LIST:
        if socket != server_socket and socket != sock :
            try :
                socket.send(message)
            except :
                # broken socket connection may be, chat client pressed ctrl+c for example
                socket.close()
                CONNECTION_LIST.remove(socket)

if __name__ == "__main__":

    # List to keep track of socket descriptors
    CONNECTION_LIST = []
    RECV_BUFFER = 4096 #exponent of 2
    PORT = 2015

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # this has no effect, why ?
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(("0.0.0.0", PORT))
    server_socket.listen(10)

    # Add server socket to the list of readable connections
    CONNECTION_LIST.append(server_socket)

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

    while 1:
        # Get the list sockets which are ready to be read through select
        read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])

        for sock in read_sockets:
            #New connection
            if sock == server_socket:
                # Handle the case in which there is a new connection recieved through server_socket
                sockfd, addr = server_socket.accept()
                CONNECTION_LIST.append(sockfd)
                print("Client (%s, %s) connected" % addr)

                broadcast_data(sockfd, "[%s:%s] entered room\n" % addr)

            #Some incoming message from a client
            else:
                # Data recieved from client, process it
                try:
                    #In Windows, sometimes when a TCP program closes abruptly,
                    # a "Connection reset by peer" exception will be thrown
                    data = sock.recv(RECV_BUFFER)
                    if data:
                        #broadcast_data(sock, "\r" + '<' + str(sock.getpeername()) + '> ' + data)
                        broadcast_data(sock, "\r" + data)

                except:
                    broadcast_data(sock, "Client (%s, %s) is offline" % addr)
                    print ("Client (%s, %s) is offline" % addr)
                    sock.close()
                    CONNECTION_LIST.remove(sock)
                    continue

    server_socket.close()

以下是客户端的代码:

#Chat Client

import socket, select, string, sys
NName = ""
def prompt() :
    sys.stdout.write('<{0}> '.format(NName))
    sys.stdout.flush()

#main function
if __name__ == "__main__":

    if(len(sys.argv) < 3) :
        print('Usage : python TCP_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.')
    print('Enter your Nickname:')
    NName = raw_input(" ")
    prompt()

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

        # Get the list sockets which are readable
        read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])

        for sock in read_sockets:
            #incoming message from remote server
            if sock == s:
                data = sock.recv(4096)
                if not data :
                    print ('\nDisconnected from chat server')
                    sys.exit()
                else :
                    #print data
                    sys.stdout.write(data)
                    prompt()

            #user entered a message
            else :
                msg = sys.stdin.readline()

                s.send("<{0}>  {1}".format(NName,msg))
                prompt()

我没有寻找对程序的任何改进,我只是想知道我应该如何使客户端从另一台计算机连接到服务器。 谢谢,

长臂猿:)

修改

好的,我意识到我可能在这里没有足够的信息:

我现在在做什么:

在OSX终端中:

python /path/to/file/TCP_Server

在另一个OSC终端(在另一台计算机上)(更换&#39; xxx.xxx ......&#39;计算机运行服务器&#39; ip addres:

python /path/to/file/TCP_Client xxx.xxx.xxx.xxx 2015

1 个答案:

答案 0 :(得分:0)

这些服务器/客户端代码对于学习和Windows 10是有益的和有用的。你必须修改智能屏幕,Windows后卫关闭。 我更喜欢你可以使用无线usb卡输入10.0.0.134/135/138的ip地址,并使用wingIDE代替IDLE编程环境。 Python比perl更好,比其他编程更灵活,就像php 7.0我是粉丝。在azure microsoft上使用python并用于电子商务目的地。 编程在语言编程水平较低时是完美的。