构建讨论板样式的服务器/客户端应用程序是客户端连接到服务器,能够发布消息,读取消息和退出。
请参阅以下客户端代码:
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)
当客户端加入时,我希望通知所有其他已连接的客户端已加入新客户端,但每个客户端可能位于代码中的不同位置(某些客户端可能位于帖子中间,坐着闲置在"你想做什么?"陈述等)。
那么我如何设置我的客户端代码,它能够在另一个客户端加入时接受来自服务器的消息?
答案 0 :(得分:1)
有很多方法可以做到这一点。这里概述了我的意思。
您熟悉"select"操作吗?它们允许您监听多个文件描述符,并在其变为活动状态时收到通知。我首先使用它来监听键盘输入和服务器消息。
然后有两件事要做。分支取决于活动的运河。如果是键盘输入,您可以将命令中继到服务器。如果它是服务器消息,则需要再次对消息类型进行分支以相应地执行操作。
编辑:永远不要假设服务器消息是什么。即使您可能刚刚发送了查询,服务器也可能会发送有关其他内容的数据。