Skip to content

Commit 8e46875

Browse files
committed
add udp sample
1 parent 5e1514c commit 8e46875

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

py3/socket/udp_client.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import socket
5+
6+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
7+
8+
for data in [b'Michael', b'Tracy', b'Sarah']:
9+
# 发送数据:
10+
s.sendto(data, ('127.0.0.1', 9999))
11+
# 接收数据:
12+
print(s.recv(1024).decode('utf-8'))
13+
14+
s.close()

py3/socket/udp_server.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import socket
5+
6+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
7+
8+
# 绑定端口:
9+
s.bind(('127.0.0.1', 9999))
10+
11+
print('Bind UDP on 9999...')
12+
13+
while True:
14+
# 接收数据:
15+
data, addr = s.recvfrom(1024)
16+
print('Received from %s:%s.' % addr)
17+
reply = 'Hello, %s!' % data.decode('utf-8')
18+
s.sendto(reply.encode('utf-8'), addr)

0 commit comments

Comments
 (0)