我设法将图像从客户端发送到服务器,但是当我尝试从服务器向客户端发送任何内容时,它似乎无法正常工作。
以下是代码:
客户端:
import socket
import pickle
host = socket.gethostname()
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host , port))
f = open("test.png", "rb")
while True:
veri = f.read()
if not veri:
break
s.send(veri)
f.close()
print "image successfully sent"
data = s.recv(1024)
#data_arr=pickle.loads(data)
print "data recieved is :",data
#s.close()
服务器:
import socket
import pickle
from PIL import Image
import os
host = socket.gethostname()
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(5)
client , adress = s.accept()
print "successfully connected to",adress
f = open("server.png", "wb")
while True:
veri = client.recv(1024)
if not veri:
break
f.write(veri)
f.close()
print "image recieved successfully"
#T= os.path.abspath(f.name)
#print "the path of the image is ",T
#data=pickle.dumps(T)
client.send(str(9))
print "binary data sent"
client.close()
图像已成功从客户端发送到服务器,但当我尝试发送字符串时,一切都停止工作。
答案 0 :(得分:1)
import socket
class node(object):
def __init__(self, nodeType):
self.port = 80
self.addr = socket.gethostname()
if nodeType == "client":
self.node = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.node.connect((self.addr, self.port))
if nodeType == "server":
self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.serv.bind((self.addr, self.port))
self.serv.listen(5)
self.node, self.addr = self.serv.accept()
def recv_file(self):
file = bytearray(self.node.recv(1024))
while b"\r\n\r\n" not in file:
file += self.node.recv(1024)
name = input("File received, enter file name to save!\n>>> ")
with open(name, "wb") as f:
f.write(bytes(file))
def send_file(self, name):
self.node.sendall(open(name, "rb").read() + b"\r\n\r\n")
print("The file was successfully sent!")
服务器:
client = node("server")
client.send_file("<File Name>") # use method for sending files
client.recv_file() # use method for reciving files
客户端:
server = node("client")
server.send_file("<File Name>") # use method for sending files
server.recv_file() # use method for reciving files