"""author = 陈俊龙"""
===============服务端套接字=============
import socket
class Data:
def __init__(self, path):
self.path = path
def add_bdata(self, data: bytes):
with open(self.path, 'ab') as f:
f.write(data)
def raed_bdata(self):
with open(self.path, 'rb') as f:
return f.read()
def add_data(self, data: str):
with open(self.path, 'a', encoding='utf8') as f:
f.write(data)
def read_data(self):
with open(self.path, 'r', encoding='utf8') as f:
return f.read()
def write_data(self, data):
with open(self.path, 'w', encoding='utf8') as f:
f.write(data)
server = socket.socket()
server.bind(('10.7.160.62', 8888))
server.listen(10)
while True:
print('正在监听中....')
connection, adr = server.accept()
while True:
con = connection.recv(1024)
re_message = con.decode(encoding='utf8')
print('客户端:', adr, re_message, sep='')
if re_message == '我要图片':
bdata = Data('./server_flies/20190207212637.jpg')
jpg = bdata.raed_bdata()
connection.send(jpg)
print('*****图片发送完成*****')
elif re_message == '我要在线沟通':
while True:
con = connection.recv(1024)
re_message = con.decode(encoding='utf8')
print(re_message)
if re_message == '拜拜':
break
message = input('请输入你想说的话:')
connection.send(message.encode())
if message == '拜拜':
break
elif re_message == '我要传图片':
d1 = Data('./flies/count.txt')
num = int(d1.read_data())
while True:
con = connection.recv(1024)
ab1 = Data('./server_flies/%d.jpg' % num)
ab1.add_bdata(con)
if len(con) < 1024:
break
d1.write_data(str(num + 1))
print('*****图片接收完成*****')
print('当前连接中断')
===============客户端套接字=============
import socket
class Data:
def __init__(self, path):
self.path = path
def add_bdata(self, data: bytes):
with open(self.path, 'ab') as f:
f.write(data)
def raed_bdata(self):
with open(self.path, 'rb') as f:
return f.read()
def add_data(self, data: str):
with open(self.path, 'a', encoding='utf8') as f:
f.write(data)
def read_data(self):
with open(self.path, 'r', encoding='utf8') as f:
return f.read()
def write_data(self, data):
with open(self.path, 'w', encoding='utf8') as f:
f.write(data)
client = socket.socket()
client.connect(('10.7.160.62', 8888))
while True:
print('请说你要图片还是沟通,或者你要给服务器传图片')
message = input('请输入:')
send_mess = message.encode()
client.send(send_mess)
if message == '我要图片':
d1 = Data('./flies/count.txt')
num = int(d1.read_data())
while True:
data = client.recv(1024)
c1 = Data('./client_flies/%d.jpg' % num)
c1.add_bdata(data)
if len(data) < 1024:
break
d1.write_data(str(num+1))
print('*****图片接收完成*****')
elif message == '我要在线沟通':
while True:
message = input('请输入你想说的话:')
client.send(message.encode())
if message == '拜拜':
break
message = client.recv(1024)
print(message.decode(encoding='utf8'))
if message.decode(encoding='utf8') == '拜拜':
break
elif message == '我要传图片':
path = input('请输入图片路径:') # './client_flies/new.jpg'
db1 = Data(path)
client.send(db1.raed_bdata())
print('*****图片发送成功*****')