gpt4 book ai didi

python - 为什么使用 python 从客户端接收图像后无法从服务器向客户端发送任何内容?

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:11 25 4
gpt4 key购买 nike

我设法将图像从客户端发送到服务器,但是当我尝试从服务器向客户端发送任何内容时,它似乎不起作用。

代码如下:

客户:

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()

图像已成功从客户端发送到服务器,但是当我尝试发送字符串时,一切都停止工作。

最佳答案

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

关于python - 为什么使用 python 从客户端接收图像后无法从服务器向客户端发送任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43536769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com