亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

套接字聊天室 - python 3.7

套接字聊天室 - python 3.7

牛魔王的故事 2021-11-02 19:35:09
這是我一直在開發的python聊天室,它使您可以通過python與同一網絡上的其他人聊天主持人:import socketimport sysimport times = socket.socket()host = socket.gethostname()port = 8080s.bind((host,port))print("")print("Sever adress is", host)print("")name = input(str("Please enter your username : "))s.listen(1)print("")print("Waiting for any incoming connections ... ")print("")conn, addr = s.accept()print("Recieved connection")#connection done ###s_name = conn.recv(1024)s_name = s_name.decode()print("")print(s_name, "has connected to the chat room")print("")conn.send(name.encode())## messaging loop ##while 1:    message = input(str("Please enter enter your message : "))    print("")    conn.send(message.encode())    message = conn.recv(1024)    message = message.decode()    print("")    print(name,": ",message)    print("")客戶:import socketimport sysimport timeprint("Welcome to python chat ")print("")print("Initiallsing....")time.sleep(1)s = socket.socket()print("")host = input(str("Please enter server adress : "))print("")name = input(str("Please enter your name : "))port = 8080print("")time.sleep(1)s.connect((host,port))print("Connected...")## Conection done ##s.send(name.encode())s_name = s.recv(1024)s_name = s_name.decode()print("")print( s_name, "has joined the chat room ")while 1:    message = s.recv(1024)    message = message.decode()    print("")    print(name,": ",message)    print("")    message = input(str("Please enter your enter message : "))    print("")    s.send(message.encode())我有兩個問題,第一個問題是它一次只允許一個人說話,我的意思是說如果你先發送一條消息,你將不被允許發送另一條消息,直到另一個人回應. 第二個問題是此代碼僅適用于 2 個用戶,我希望它適用于多個用戶
查看完整描述

3 回答

?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

您需要為發送和接收創建兩個單獨的線程。您編寫循環的方式不適用于同時進行雙向通信。因為在發送消息后,循環正在等待接收某些東西。[如果您想通過互聯網運行代碼,請替換localhost為所需的 IP 地址行HOST = 'localhost'] 讓我分享一個解決方案(這是我在 TAing 本科網絡課程時完成的示例解決方案):


我已經在 Linux 機器(Ubuntu 18.04)上測試了代碼。我有學生在他們的 Mac 上成功運行了這個。我不確定它是否在 Windows 機器上運行。即使它在 Windows 機器上不起作用,一些小的修改也應該可以解決問題。


服務端代碼(你需要先運行這個): chatServerDuplex.py


# Import socket module

from socket import *

import threading

import sys # In order to terminate the program


FLAG = False  # this is a flag variable for checking quit


# function for receiving message from client

def recv_from_client(conn):

    global FLAG

    try:

        # Receives the request message from the client

        while True:

            if FLAG == True:

                break

            message = conn.recv(1024).decode()

            # if 'q' is received from the client the server quits

            if message == 'q':

                conn.send('q'.encode())

                print('Closing connection')

                conn.close()

                FLAG = True

                break

            print('Client: ' + message)

    except:

        conn.close()



# function for receiving message from client

def send_to_client(conn):

    global FLAG

    try:

        while True:

            if FLAG == True:

                break

            send_msg = input('')

            # the server can provide 'q' as an input if it wish to quit

            if send_msg == 'q':

                conn.send('q'.encode())

                print('Closing connection')

                conn.close()

                FLAG = True

                break

            conn.send(send_msg.encode())

    except:

        conn.close()



# this is main function

def main():

    threads = []

    global FLAG


    # TODO (1) - define HOST name, this would be an IP address or 'localhost' (1 line)

    HOST = 'localhost'

    # TODO (2) - define PORT number (1 line) (Google, what should be a valid port number)

    # make sure the ports are not used for any other application

    serverPort = 6789


    # Create a TCP server socket

    #(AF_INET is used for IPv4 protocols)

    #(SOCK_STREAM is used for TCP)

    # TODO (3) - CREATE a socket for IPv4 TCP connection (1 line)

    serverSocket = socket(AF_INET, SOCK_STREAM)


    # Bind the socket to server address and server port

    # TODO (4) - bind the socket for HOSR and serverPort (1 line)

    serverSocket.bind((HOST, serverPort))


    # Listen to at most 1 connection at a time

    # TODO (5) - listen and wait for request from client (1 line)

    serverSocket.listen(1)


    # Server should be up and running and listening to the incoming connections

    print('The chat server is ready to connect to a chat client')

    # TODO (6) - accept any connection request from a client (1 line)

    connectionSocket, addr = serverSocket.accept()

    print('Sever is connected with a chat client\n')


    t_rcv = threading.Thread(target=recv_from_client, args=(connectionSocket,))

    t_send = threading.Thread(target=send_to_client, args=(connectionSocket,))

    # call the function to receive message server

    #recv_from_server(clientSocket)

    threads.append(t_rcv)

    threads.append(t_send)

    t_rcv.start()

    t_send.start()


    t_rcv.join()

    t_send.join()



    # closing serverScoket before exiting

    print('EXITING')

    serverSocket.close()

    #Terminate the program after sending the corresponding data

    sys.exit()



# This is where the program starts

if __name__ == '__main__':

    main()

客戶端代碼: chatClientDuplex.py


from socket import *

import threading

import sys



FLAG = False  # this is a flag variable for checking quit


# function for receiving message from client

def send_to_server(clsock):

    global FLAG

    while True:

        if FLAG == True:

            break

        send_msg = input('')

        clsock.sendall(send_msg.encode())


# function for receiving message from server

def recv_from_server(clsock):

    global FLAG

    while True:

        data = clsock.recv(1024).decode()

        if data == 'q':

            print('Closing connection')

            FLAG = True

            break

        print('Server: ' + data)


# this is main function

def main():

    threads = []

    # TODO (1) - define HOST name, this would be an IP address or 'localhost' (1 line)

    HOST = 'localhost'  # The server's hostname or IP address

    # TODO (2) - define PORT number (1 line) (Google, what should be a valid port number)

    PORT = 6789        # The port used by the server


    # Create a TCP client socket

    #(AF_INET is used for IPv4 protocols)

    #(SOCK_STREAM is used for TCP)

    # TODO (3) - CREATE a socket for IPv4 TCP connection (1 line)

    clientSocket = socket(AF_INET, SOCK_STREAM)


    # request to connect sent to server defined by HOST and PORT

    # TODO (4) - request a connection to the server (1 line)

    clientSocket.connect((HOST, PORT))

    print('Client is connected to a chat sever!\n')




    # call the function to send message to server

    #send_to_server(clientSocket)

    t_send = threading.Thread(target=send_to_server, args=(clientSocket,))

    # call the function to receive message server

    #recv_from_server(clientSocket)

    t_rcv = threading.Thread(target=recv_from_server, args=(clientSocket,))

    threads.append(t_send)

    threads.append(t_rcv)

    t_send.start()

    t_rcv.start()


    t_send.join()

    t_rcv.join()


    print('EXITING')

    sys.exit()


# This is where the program starts

if __name__ == '__main__':

    main()



查看完整回答
反對 回復 2021-11-02
?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

System123456 問題是當服務器偵聽并且客戶端連接到它時,您構建了一個客戶端 - 服務器系統。嘗試查看點對點系統,而不是每個節點都是平等的。為了構建聊天室,您可能會查看 DHT 節點。


查看完整回答
反對 回復 2021-11-02
?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

您的第一個問題可能是由于默認情況下 python 套接字是阻塞的。這意味著,例如,在 line 上message = s.recv(1024),您的程序將繼續偵聽,并且在收到某些內容之前不會繼續執行腳本的其余部分。

如果您希望兩個人能夠同時接收和發送,您可能需要研究非阻塞套接字和一些異步編程。官方文檔中的此操作方法可能對您有所幫助:https : //docs.python.org/2/howto/sockets.html#non-blocking-sockets


查看完整回答
反對 回復 2021-11-02
  • 3 回答
  • 0 關注
  • 226 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號