【问题标题】:sending json.dumps() via python sockets通过 python 套接字发送 json.dumps()
【发布时间】:2018-10-25 11:48:06
【问题描述】:

我要创建的是一组服务器和客户端脚本;服务器脚本提示用户输入原始输入,将该输入存储在字典中并使用 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 变量中定义了发送数据的地址,但显然不是?

【问题讨论】:

    标签: python json sockets server client


    【解决方案1】:

    试试:

    conn, addr = s.accept()
    ...
    conn.send(serverMessage)
    

    即将s. 调用替换为conn.,它表示来自客户端的已接受套接字连接。

    来自Python socket API

    socket.accept()

    接受连接。套接字必须绑定到一个地址并监听连接。 返回值是一对 (conn, address) 其中 conn 是一个新的套接字 可用于在连接上发送和接收数据的对象,以及地址 是绑定到连接另一端的套接字的地址。

    页面末尾提供了示例。

    另见Python Socket Programming Howto

    【讨论】:

    • 这很棒!非常感谢!你有没有机会给我解释一下为什么 s.accept() 需要这两个变量?或者指向一本好书的方向,在那里我可以学到更多? =D
    • 我已经扩展了答案。有很多教程可用。只是谷歌python服务器套接字示例
    猜你喜欢
    • 2022-01-15
    • 2015-08-28
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 2014-03-31
    • 2014-09-01
    • 1970-01-01
    相关资源
    最近更新 更多