python - Python Sockets:客户端和服务器都相互发送和接收数据?
问题描述
如何让套接字发送数据然后接收数据?我在网上遵循了一些教程,可以让服务器将数据发送到客户端。我的目标是将腌制图像从客户端发送到服务器,然后让服务器以文本响应。有人可以提供这种双向通信的快速示例吗?
解决方案
我不知道双向通信或腌制图像的确切含义,但我可以为您提供一个示例 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()
推荐阅读
- c - Arduino 或 C 中数据类型约束内的布尔运算和二进制协议定义
- python - Solve single variable equation using if, else and while statements in python
- javascript - reactjs中的传播语法“...this.props”感觉很奇怪
- python - 为什么我的直方图在 python 的这个随机问题图中看起来很奇怪?
- python - Python Beautifulsoup - 阅读问题
- javascript - 在javascript中使用正则表达式匹配一串单词和数字
- rust - Serde 能否根据字段的值将 JSON 反序列化为一组类型中的一种?
- swift - CollectionView 单元格困惑
- asp.net-mvc - Azure + ASP.Net + System.UnauthorizedAccessException:对路径“/Content/img/CourseImages”的访问被拒绝
- c++ - 将父类对象转换为子对象的问题