1. 程式人生 > >Python網絡編程UDP服務器與客服端簡單例子

Python網絡編程UDP服務器與客服端簡單例子

... ket add and cti while NPU inpu dto

[轉載] https://blog.csdn.net/hu330459076/article/details/7868028

UDP服務器代碼:

#!/usr/bin/env python
# -*- coding:UTF-8 -*-

from socket import *
from time import ctime

HOST = 127.0.0.1
PORT = 21567
BUFSIZE = 1024

ADDR = (HOST,PORT)

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

while True: print wating for message... data, addr = udpSerSock.recvfrom(BUFSIZE) udpSerSock.sendto([%s] %s%(ctime(),data),addr) print ...received from and retuned to:,addr udpSerSock.close()


UDP客服端代碼:

#!/usr/bin/env python

from socket import *

HOST = localhost
PORT = 21567 BUFSIZE = 1024 ADDR = (HOST, PORT) udpCliSock = socket(AF_INET, SOCK_DGRAM) while True: data = raw_input(>) if not data: break udpCliSock.sendto(data,ADDR) data,ADDR = udpCliSock.recvfrom(BUFSIZE) if not data: break print data udpCliSock.close()

Python網絡編程UDP服務器與客服端簡單例子