下面是代码, server 端会在 recv 上挂住 这个是为什么?
server:
# -*- coding: UTF-8 -*-
# 导入库
import socket, threading, os, uuid, sys
SIZE = 1024 * 1024 * 5
filename = str(uuid.uuid4()) + '.jpg'
# 检查当前目录下是否有等下要命名的图片,有的话删除之
def checkFile():
list = os.listdir('.')
for iterm in list:
if iterm == filename:
os.remove(iterm)
print('remove')
else:
pass
# 接受数据线程
def tcplink(sock, addr):
# def tcplink():
print('Accept new connection from %s:%s...' % addr)
# sock.send(b'Welcome from server!')
print('receiving, please wait for a second ...')
while True:
try:
data = sock.recv(SIZE)
if not data :
print('reach the end of file')
break
elif data == 'begin to send':
print('create file')
checkFile()
with open(filename, 'wb') as f:
pass
else:
with open(filename, 'ab') as f:
f.write(data)
except:
print("Unexpected error:", sys.exc_info()[0])
break
print('msg send')
sock.send(b'Welcome from server!')
sock.close()
print('receive finished')
print('Connection from %s:%s closed.' % addr)
# 创建一个 socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 监听端口(这里的 ip 要在不同的情况下更改)
s.bind(('127.0.0.1', 9999))
# 每次只允许一个客户端接入
s.listen(2)
print('Waiting for connection...')
while True:
# 建立一个线程用来监听收到的数据
sock, addr = s.accept()
t = threading.Thread(target = tcplink, args = (sock, addr))
# 线程运行
t.start()
client:
# -*- coding: UTF-8 -*-
import socket
SIZE = 1024 * 1024 * 5
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect(('127.0.0.1', 9999))
# 接收欢迎消息:
with open('./image.png', 'rb') as f:
data = f.read()
s.sendall(data)
print('sended !')
data = s.recv(SIZE)
# print(data)
s.close()
print('connection closed')
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.