1、TCP服务端的创建
import socket
# 创建tcp套接字
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址
sockfd.bind(('0.0.0.0', 6663))
# 设置监听
sockfd.listen(2)
# 等待客户端连接
while True:
print('Waiting for connect.....')
try:
connfd, addr = sockfd.accept()
print('Connect from {0}'.format(addr))
except KeyboardInterrupt as e:
break
# 收消息
while True:
data = connfd.recv(5)
if not data:
break
print("接受到来自{0}的{1}".format(addr, data.decode()))
# 发信息
num = connfd.send(b'Thanks')
print('Send {0} bytes'.format(num))
# 关闭连接
connfd.close()
sockfd.close()
2、TCP客户端的创建
import socket
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
sockfd.connect(('127.0.0.1', 8888))
print('连接到服务端...')
# 收发信息
while True:
msg = input('>>')
if msg == '':
break
num = sockfd.send(msg.encode())
data = sockfd.recv(1024)
print('from server:{0}'.format(data.decode()))
sockfd.close()
3、TCP的应用—文件上传
"""
文件上传服务端
"""
import socket
sockdf = socket.socket()
sockdf.bind(('0.0.0.0', 8888))
sockdf.listen(5)
print('Waiting for connect.....')
connfd, addr = sockdf.accept()
print('Connect from {0}'.format(addr))
filename = connfd.recv(1024).decode()
f = open('/home/xiaohuo/PycharmProjects/Project/Network_programming/'+filename, 'wb')
while True:
data = connfd.recv(1024)
if data == b'ok':
break
f.write(data)
f.close()
connfd.close()
sockdf.close()
"""
文件上传客户端
"""
import socket, time
sockdf = socket.socket()
sockdf.connect(('127.0.0.1', 8888))
filename = input('file_dir:')
f = open(filename, 'rb')
sockdf.send((filename.split('/')[-1]).encode())
while True:
data = f.read(1024)
if not data:
time.sleep(0.1)
sockdf.send('ok'.encode())
break
sockdf.send(data)
f.close()
sockdf.close()