13、网络编程
#
TCP编程
#
#service.py
# -*- coding: UTF-8 -*-
import socket
import threading
import time
def tcplink(skt, adr):
print('Accept new connection from %s:%s...' % adr)
skt.send(b'Welcome!')
while True:
# 每次接收1K字节
data = skt.recv(1024)
time.sleep(2)
if not data or data.decode('utf-8') == 'exit':
break
skt.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))
skt.close()
print('Connection from %s:%s closed.' % adr)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9000))
# 等待连接的最大数量5
s.listen(5)
print('Waiting for connection...')
while True:
sock, addr = s.accept()
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()
#client.py
# -*- coding: UTF-8 -*-
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect(('127.0.0.1', 9000))
# 接收欢迎消息:
print(s.recv(1024).decode('utf-8'))
for data in [b'Michael', b'Tracy', b'Sarah']:
# 发送数据:
s.send(data)
print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()
UDP编程
#
#server.py
# -*- coding: UTF-8 -*-
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定端口:
s.bind(('127.0.0.1', 9000))
print('BInd udp on 9000...')
while True:
# 接收数据:
data, addr = s.recvfrom(1024)
print('Received from %s:%s.' % addr)
s.sendto(b'Hello, %s!' % data, addr)
#client.py
# -*- coding: UTF-8 -*-
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for data in [b'Michael', b'Tracy', b'Sarah']:
# 发送数据:
s.sendto(data, ('127.0.0.1', 9000))
# 接收数据:
print(s.recv(1024).decode('utf-8'))
s.close()