聊天程序螺纹

时间:2017-01-16 06:30:30

标签: python multithreading python-3.x

我正在尝试使用python构建一个小型聊天服务器/客户端。到目前为止,我认为我设法设置它,但我遇到了问题。我想将程序设置为多线程以使服务器监听连接,并继续监听数据,然后让主程序循环保留在客户端发送中。这是我的代码,我在启动listen函数时遇到了一个问题,它告诉我参数必须是一个可迭代的而不是套接字。

import socket
import platform
import os
import threading

'''Define Globals'''
HOST = ""
PORT = 25000
ADDR = (HOST, PORT)
BUF = 1024


def client_send():

    server_ip = input("[+] Server's IP to connect to: ")

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((server_ip, 25000))

    data_thread = threading.Thread(target=client_listen, args=(client_socket))
    data_thread.start()

    while True:
        data = input("[%s] => " % os.getlogin())
        client.send(str.encode("[%s] => " + data % os.getlogin()))


def client_listen(client):

    while True:
        print(client.recv(BUF))


def server_loop():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(ADDR)
    server.listen(10)

    print("[+] Server started on %s" %platform.node())
    print("[+] Awaitiing connection from client..")

    while True:
        client_socket, client_addr = server.accept()
        print("[+] New Connection from %s" %client_addr[0])


def main():

   server_thread = threading.Thread(target=server_loop)

   while True:

       try:
            print("Select Operating Mode")
            print("---------------------")
            print("1. Server Mode")
            print("2. Client Mode")
            mode = int(input("Enter mode of operation: "))
            print("")
            print("")
            if mode in [1,2]:
                break
            else:
                raise ValueError
       except ValueError:
           print("Enter either (1) for Server or (2) for Client")


   if mode == 1:
        server_thread.start()
   elif mode == 2:
        client_send()



main()

1 个答案:

答案 0 :(得分:1)

您需要使参数成为元组

您应该在参数列表后面提供额外的逗号,如下所示:

data_thread = threading.Thread(target=client_listen, args=(client_socket,))

当你研究两者的类型时,可以看出差异:

>>> type((client_socket))
<class 'socket._socketobject'>
>>> type((client_socket,))
<type 'tuple'>