python - 通过 python 套接字发送 json.dumps()
问题描述
我要创建的是一组服务器和客户端脚本;服务器脚本提示用户输入原始输入,将该输入存储在字典中并使用该json.dumps()
函数将其转换为 json。然后将转换后的字典存储在jasonFile
变量中,然后将其发送给客户端。json 字典正在工作,但我正在努力解决网络方面的问题。
这是我的服务器代码:
def Main():
host = '0.0.0.0'
port = 5000
s.bind((host, port))
s.listen(5)
print "Server Started"
while True:
addr = s.accept()
print "Client Connected from IP: " + str(addr)
serverMessage = "Connection Established: Would you like to download the Json dictionary?"
s.send(serverMessage)
clientReply = s.recv(1024)
if clientReply in ['Y', 'y', 'Yes', 'yes', 'YES']:
s.send(jasonFile)
s.close()
else:
print "Connection from " + addr + " closed!"
s.send("Connection Error!")
s.close()
这是我的客户代码:
def Main():
host = raw_input("Please enter the server IP you wish to connect to: ")
port = 5000
#define client to use socket module to connect via IPV4 and TCP only
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
serverMessage = client.recv(1024)
print serverMessage
clientReply = raw_input("Type 'Yes' To download dictionary")
if clientReply in ['Y', 'Yes', 'y', 'yes', 'YES']:
client.send(clientReply)
jasonRecv = client.recv(1024)
print jasonRecv
else:
client.close()
print "Disconnected from server!"
我还没有将json数据转换回客户端上的字符串,因为当客户端尝试连接时服务器会抛出一个错误。
我从 IDLE 得到的错误信息是:
Server Started
Client Connected from IP: (<socket._socketobject object at 0x000000000401E048>, ('127.0.0.1', 34375))
Traceback (most recent call last): File "D:/Server.py", line 105, in <module>
Main()
File "D:/Server.py", line 94, in Main
s.send(serverMessage)
error: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
我以为我在addr
变量中定义了将数据发送到的地址,但显然不是?
解决方案
尝试:
conn, addr = s.accept()
...
conn.send(serverMessage)
i.e. replace s.
calls with conn.
which represents the accepted socket connection from the client.
From the Python socket API:
socket.accept()
Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.
Examples are provided at the end of the page.
Also see the Python Socket Programming Howto
推荐阅读
- bixby - 你是如何理解 Bixby 编程的?
- python - matplotlib xkcd() 显示正确的字体,但不显示线条样式
- matplotlib - 你能提取 Matplotlib 对数轴中使用的对数的底吗?
- javascript - document.getElementById().value 没有返回正确的值
- javascript - 无法使用 Fargate 上托管的 NextJS 应用检索 process.env 变量
- node.js - 我怎样才能制作这样的用户界面......我的意思是这些曲线和线条以及反应原生的东西
- ios - 使用 Expo 进行排毒测试 - 无法连接到模拟器
- angular - Angular Reactive表单嵌套FormGroup中的空值
- javascript - 如何将 CSV 或 XLS 内容从 Gmail 中的下一个可用行添加到 Google 表格中?
- php - 如何在 WooCommerce 中 x 分钟或 x 小时后取消待处理的付款订单