【问题标题】:Python: How to send message to client from server at any time?Python:如何随时从服务器向客户端发送消息?
【发布时间】:2015-11-27 19:45:15
【问题描述】:

我正在构建一个讨论板风格的服务器/客户端应用程序,客户端连接到服务器,能够发布消息、阅读消息和退出。

见下面的客户端代码:

import socket

target_host = "0.0.0.0"
target_port = 9996

#create socket object
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#connect the client
client.connect((target_host,target_port))

#receiving user name prompt
print client.recv(1024)

usrname = str(raw_input()) 

#send username
client.send(usrname)

#check if username was unique
while client.recv(1024) == "NU": #should exit once "ACK" received
    print client.recv(1024) #print username promt again

    usrname = str(raw_input()) #client enters in another username
    client.send(usrname)

#receive user joined message/welcome message/help menu
response = client.recv(1024)
print response

print client.recv(1024)

#loops until client disconnects
while True:

    request = str(raw_input("\n\nWhat would you like to do? "))
    client.send(request)

    if request == "-h":
        help_menu = client.recv(1024) 
        print help_menu

    elif request == "-p":
        #get subject
        subject_request = client.recv(1024)
        print subject_request

        subject = str(raw_input())
        client.send(subject)

        #get contents of post
        contents_request = client.recv(1024)
        print contents_request

        contents = str(raw_input())
        client.send(contents)

        #get post notification 
        message_post = client.recv(1024)
        print message_post

    elif request == "-r":
        #get id value of post 
        id_request = client.recv(1024)
        print id_request

        message_id = str(raw_input())
        client.send(message_id)

        #get contents of post 
        message_contents = client.recv(2048)
        print message_contents

    elif request == "-q":
       break
    else:
        print client.recv(1024)

当客户加入时,我希望通知所有其他已连接的客户新客户已加入,但每个客户可能位于代码中的不同点(有些可能在帖子中间,坐在空闲在“你想做什么?”声明等)。

那么我将如何设置我的客户端代码,使其能够在另一个客户端加入时接受来自服务器的消息?

【问题讨论】:

    标签: python sockets server client


    【解决方案1】:

    有很多方法可以做到这一点。这里是我将如何做的概述。

    您熟悉"select" 操作吗?它们允许您侦听多个文件描述符,并在其中一个变为活动状态时收到通知。我将首先使用它来监听键盘输入和服务器消息。

    那么有两件事要做。根据活跃的运河分支。如果是键盘输入,您可以将命令中继到服务器。如果是服务器消息,则需要在消息类型上再次分支以采取相应措施。

    编辑:永远不要假设服务器消息是关于什么的。即使您可能刚刚发送了查询,服务器也可能正在发送有关其他内容的数据。

    【讨论】:

    • 我不熟悉该操作,但我会阅读并尝试弄清楚。从你说的情况来看,这正是我希望做的。谢谢!
    猜你喜欢
    • 2019-07-09
    • 2013-06-24
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 2022-07-15
    相关资源
    最近更新 更多