基于UDP协议的socket
PS:udp是无连接的,先启动那一端都不会报错
server端
import socket # 导入socket模块
udp_sk = socket.socket(type=socket.SOCK_DGRAM) # 创建一个服务器套接字
udp_sk.bind(('127.0.0.1', 8080)) # 绑定服务器套接字
msg, addr = udp_sk.recvfrom(1024) # 接收客户端信息
print(msg) # 输出客户端的信息
udp_sk.sendto(b'hi', addr) # 向客户端发送信息
udp_sk.close() # 关闭服务器套接字
client端
import socket
sk = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1', 8080)
udp_sk = sk.sendto(b'hello', ip_port)
msg, addr = udp_sk.recvfrom(1024)
print(msg.decode('utf-8'))
QQ聊天
server端
import socket
ip_port = ('127.0.0.1', 8080)
udp_server_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_server_sock.bind(ip_port)
while True:
qq_msg, addr = udp_server_sock.recvfrom(1024)
print('来自%s:%s' % (str(addr), qq_msg.decode('utf-8')))
back_msg = input('回复消息:').strip()
udp_server_sock.sendto(back_msg.encode('utf-8'), addr)
client端
import socket
BUFSIZE = 1024
udp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
qq_name_dic = {'路人甲': ('127.0.0.1', 8080),
'路人乙': ('127.0.0.1', 8080),
'路人丙': ('127.0.0.1', 8080)}
while True:
qq_name = input('请选择聊天对象,输入q结束程序:').strip()
if qq_name == 'q': break
while True:
msg = input('请输入消息,回车发送,输入q结束和他的聊天:').strip()
if msg == 'q': break
if not msg or not qq_name or qq_name not in qq_name_dic: continue
udp_client_socket.sendto(msg.encode('utf-8'), qq_name_dic[qq_name])
msg, addr = udp_client_socket.recvfrom(BUFSIZE)
print('来自 %s 的一条消息:%s'%(str(addr), msg.decode('utf-8')))
udp_client_socket.close()
时间服务器
server端
import socket
import time
sk = socket.socket()
sk.bind(('127.0.0.1', 8090))
sk.listen()
while True:
conn, addr = sk.accept()
while True:
ret = conn.recv(1024).decode('utf-8')
time.sleep(1)
new_time = time.strftime(ret, time.localtime(time.time()))
conn.send(new_time.encode('utf-8'))
client端
import socket
sk = socket.socket()
sk.connect(('127.0.0.1', 8090))
while True:
sk.send('%Y-%m-%d %X'.encode('utf-8'))
msg = sk.recv(1024)
print('\r' + str(msg.decode('utf-8')), end='', flush=True)
socket参数的详解
socket.socket(family=AF_INET,type=SOCK_STREAM,proto=0,fileno=None)
创建socket对象的参数说明