Python3——简单的UDP实例

                            Python3——简单的UDP实例

 

服务器:创建套接字——绑定套接字——数据接收/发送

客户端:创建套接字——数据接收/发送

 

"""
server.py
encode()/decode()
"""
from socket import *
from time import ctime

HOST = ''
PORT = 11113
BUFSIZE = 4096
ADDR = (HOST, PORT)

udpServer = socket(AF_INET, SOCK_DGRAM)
udpServer.bind(ADDR)

while 1:
	print('waiting for message...')
	data, addr = udpServer.recvfrom(BUFSIZE)
	print(data.decode())
	if not data:
		print('---------')
		break;

	buf = '[' + ctime() + ']' + data.decode()
	udpServer.sendto(buf.encode(), addr)

udpServer.close()
"""
client.py
encode()/decode()
"""
from socket import *

HOST = 'localhost'
PORT = 11113
BUFSIZE = 4096
ADDR = (HOST, PORT)

udpClient = socket(AF_INET, SOCK_DGRAM)

while 1:
	data = input('> ')
	if not data:
		break
	udpClient.sendto(data.encode(), ADDR)
	
	data, ADDR = udpClient.recvfrom(BUFSIZE)
	print(data.decode())
	if not data:
		break
	
tcpClient.close()

 

 

 

你可能感兴趣的:(Python3)