写了详细的注释,如果有哪一行不明白,可留言哦。
# _*_ coding: utf-8 _*_
__author__ = ‘xiaoke‘
__date__ = ‘2018/6/13 14:39‘
# 这个脚本创建一个TCP服务器,它接收来自客户端的消息,然后将消息加上时间戳前缀并返回客户端
import socket
from time import ctime
HOST = ‘‘
PORT = 21567
BUFSIZ = 4096
ADDR = (HOST, PORT)
# 创建TCP套接字
tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 创建UDP套接字
# udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tcpSock.bind(ADDR) # 将地址绑定到套接字上
tcpSock.listen(5) # 设置并启动TCP监听器
while True:
print("waiting for connection....")
tcpCliSock, addr = tcpSock.accept() # 被动接收TCP客户端连接,一直等待直到连接到达(阻塞)
print("... connected from", addr)
while True:
data = tcpCliSock.recv(BUFSIZ) # 接收TCP消息
# print(data)
# 如果有数据加上时间戳后返回给客户端,因为只接受字节数据,所以把数据使用bytes函数转换
if not data:
break
tcpCliSock.send(bytes(‘[%s] %s‘ % (ctime(), data.decode(‘utf-8‘)), ‘utf-8‘))
tcpCliSock.close()
# tcpSock.close()
# _*_ coding: utf-8 _*_
__author__ = ‘xiaoke‘
__date__ = ‘2018/6/13 16:01‘
import socket
import sys
HOST = ‘127.0.0.1‘
PORT = 21567
BUFSIZ = 4096
ADDR = (HOST, PORT)
# 创建客户端TCP连接
tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
try:
tcpCliSock.connect(ADDR)
except Exception as e:
print("连接服务器失败:",e)
sys.exit(-1)
while True:
data = input(‘> ‘)
if not data:
break
# 循环发送数据,直到没有数据发送退出
tcpCliSock.send(bytes(data, encoding=‘utf-8‘))
# 接收服务端返回的消息,如果没有消息返回,也将退出循环
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode(‘utf-8‘))
tcpCliSock.close()
原文地址:http://blog.51cto.com/kexiaoke/2128959