[python]代码库
# sockert服务端
import socket
# 客户端
# 声明协议类型,同时生成socket对象
client = socket.socket()
#
client.connect(('localhost', 9999))
# python3 接收字节流数据
while True:
msg = input('>>:').strip()
if len(msg) == 0: # 输入不能为空
continue
client.send(msg.encode('utf-8'))
data = client.recv(1024) # 1024字节的数据
print(data)
print(data.decode())
# socket客户端
# -*- coding: UTF-8 -*-
import socket
# 声明协议类型
server = socket.socket()
# 绑定本地网卡(多网卡选择),端口
server.bind(('localhost', 9999))
# 监听端口
server.listen(5) # 监听
while True:
conn, address = server.accept()
print("进入等待时间....")
while True:
print("收到连接....")
# 接收数据
data_server = conn.recv(1024)
if not data_server: # 这里判断客户端断开的情况,不控制会无限循环
print('client is lost...')
break
print('receive:', data_server.decode())
# 返回一个值
conn.send(data_server)