pythonsockets:客户端和服务器都从对方发送和接收数据?

2024-10-01 07:51:17 发布

您现在位置:Python中文网/ 问答频道 /正文

如何获取套接字来发送数据,然后再接收数据?我在线学习了一些教程,可以让服务器向客户端发送数据。我的目标是将一个经过pickle处理的图像从客户端发送到服务器,然后让服务器用文本响应。有人能举一个这种双向交流的例子吗


Tags: 图像文本服务器客户端目标教程pickle发送数据
1条回答
网友
1楼 · 发布于 2024-10-01 07:51:17

我不知道你所说的双向通信或pickle映像到底是什么意思,但我可以为你提供一个示例tcp套接字代码来发送映像。跳转到您要查找的代码的完整代码部分,该部分位于底部。 以下是一个服务器示例:

import socket                
  
# next create a socket object 
s = socket.socket()    
print("Initialized socket")      

port = 8986                
print("Port set to:" + str(port))

s.bind(('', port))         
  
s.listen(5)      
print("socket is waiting for client")         

while True: 
   c, addr = s.accept()      
   print('Client', addr )
  
   # send a thank you message to the client.  
   c.send('Demo'.encode()) 
  
   c.close() 

然后,客户机示例将如下所示:

import socket                

s = socket.socket()    
print("Initialized socket")      

port = 8986            
print("Port set to:" + str(port))      

s.connect(('127.0.0.1', port)) 

print(s.recv(1024).decode() )
s.close()    

现在要发送图像,您需要将pythons函数作为字节数组读取图像并发送

#On server-side
def read(self, filename):
    toRead = open(filename, "rb")

    out = toRead.read()
    toRead.close()
    
    return out
imgData = read("demo.jpg")
c.send(imgData) 

在客户端:

imgData = s.recv(1024)

def write(self, filename, data):
    toWrite = open(filename, "wb")

    out = toWrite.write(data)
    toWrite.close()

write("Demo.jpg", imgData)

完整代码服务器套接字:

import socket    
        
def read(filename):
    toRead = open(filename, "rb")

    out = toRead.read()
    toRead.close()
    
    return out
imgData = read("demo.jpg")

# next create a socket object 
s = socket.socket()    
print("Initialized socket")      

port = 8986                
print("Port set to:" + str(port))

s.bind(('', port))         
  
s.listen(5)      
print("socket is waiting for client")         

while True: 
   c, addr = s.accept()      
   print('Client', addr )
  
   print("Sending image")  
   c.send(imgData) 
  
   print(c.recv(1024).decode())
   #c.close() 

完整客户端代码:

import socket 

def write(filename, data):
    toWrite = open(filename, "wb")

    out = toWrite.write(data)
    toWrite.close()             

s = socket.socket()    
print("Initialized socket")      

port = 8986            
print("Port set to:" + str(port))      

s.connect(('127.0.0.1', port)) 

#The buffer size is important to set correctly.
#Below buffersize is 1024*8 which is about 8kB.
#Images more than 8kB will appear to be cut from the top.
#To prevent this you have to set a higher buffersize.
#Or you can have the server socket send the image length before
#sending the image byte-array.

imgData = s.recv(1024*8)
write("Demo.jpg", imgData)  

s.send("Received image".encode())
s.close()    

相关问题 更多 >