基于udp简单聊天的系统

老师博客:http://www.cnblogs.com/Eva-J/articles/8244551.html#_label4

基于udp的简单的聊天代码

说明:这段代码,显示有client向servre发送消息,然后有server在向client发送消息,简单的模拟聊天,如果有一方的聊天信息是bye的话,便会终止聊天对话,最好对方另外一方也可以同时说bye,才能结束双方的聊天信息。

server端

import socket
server=socket.socket(type=socket.SOCK_DGRAM)
ip_port=('192.168.43.155',8893)
server.bind(ip_port)
while 1:
message,address=server.recvfrom(1024)
print('来自',address,':',message.decode('utf-8'),)
server_say=input('what are you want say:').encode('utf-8')
server.sendto(server_say,address)
if 'bye' in message.decode('utf-8'):
break
server.close()

client端

import socket
client=socket.socket(type=socket.SOCK_DGRAM)
ip_port=('192.168.43.155',8893)
while 1:
client_say=input('what are you want to say?:').encode('utf-8')
client.sendto(client_say,ip_port)
message,address=client.recvfrom(1024)
ret = message.decode('utf-8')
print('来自',address,'的消息:',ret)
if ret=='bye':
break
client.close()
上一篇:CF741 D Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths


下一篇:作业MyCP中无法命令行输入的问题解决