"""author = 陳俊龍"""
===============服務(wù)端套接字=============
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('正在監(jiān)聽中....')
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('*****圖片發(fā)送完成*****')
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('當(dāng)前連接中斷')
===============客戶端套接字=============
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('請說你要圖片還是溝通钓辆,或者你要給服務(wù)器傳圖片')
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('*****圖片發(fā)送成功*****')