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)
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()
我不知道你所说的双向通信或pickle映像到底是什么意思,但我可以为你提供一个示例tcp套接字代码来发送映像。跳转到您要查找的代码的完整代码部分,该部分位于底部。 以下是一个服务器示例:
然后,客户机示例将如下所示:
现在要发送图像,您需要将pythons函数作为字节数组读取图像并发送
在客户端:
完整代码服务器套接字:
完整客户端代码:
相关问题 更多 >
编程相关推荐