Python: 使用socket实现UDP通讯

1、Server端代码

import socket
port = 8081

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('',port))
while True:
    data, addr = s.recvfrom(3000)
    print ('Received: ',data, ' from ', addr)

2、客户端代码

import socket
port=8081
host='localhost'
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto(b'hello,this is a test info !',(host,port))

3、先运行Server端代码,然后运行Client端代码,结果如下:

C:\Python27>test_udpserver.py

('Received: ', 'hello,this is a test info !', ' from ', ('127.0.0.1', 59689))

猜你喜欢

转载自sharley.iteye.com/blog/2377409