天天看点

request python 服务器主动发起的信息_Python:如何随时从服务器向客户端发送消息?...

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

参见下面的客户代码: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)

当一个客户机加入时,我希望通知所有其他连接的客户机有一个新的客户机加入,但是每个客户机在代码中可能处于不同的位置(有些客户机可能正处于post的中间,在“您想做什么?”声明等)。在

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