如何获取套接字以发送数据然后接收数据?我在线上关注了一些教程,可以让服务器将数据发送到客户端。我的目标是将腌制的图像从客户端发送到服务器,然后让服务器响应文本。有人可以提供这种双向通信的快速示例吗?
答案 0 :(得分:0)
我不知道双向通信或腌制图像的确切含义,但是我可以为您提供示例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()