简体   繁体   English

使用Python将JSON对象发送到TCP侦听器端口

[英]Sending JSON object to a tcp listener port in use Python

I have a listener on a tcp localhost: 我在TCP本地主机上有一个侦听器:

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 8192         # The port used by the server
def client_socket():
    while 1:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((TCP_IP,TCP_PORT))
        s.listen(1)
        while 1:
            print 'Listening for client...'
            conn, addr = s.accept()
            print 'Connection address:', addr
            data = conn.recv(BUFFER_SIZE)
            if data == ";" :
                conn.close()
                print "Received all the data"
                i=0
                for x in param:
                    print x
                #break
            elif data:
                print "received data: ", data
                param.insert(i,data)
                i+=1
                #print "End of transmission"
        s.close()

I am trying to send a JSON object to the same port on the local host: 我正在尝试将JSON对象发送到本地主机上的同一端口:

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 8192         # The port used by the server
def json_message(direction):

    local_ip = socket.gethostbyname(socket.gethostname())
    data = {
        'sender' : local_ip,
        'instruction' : direction
    }

    json_data = json.dumps(data, sort_keys=False, indent=2)
    print("data %s" % json_data)

    send_message(json_data)

    return json_data



def send_message(data):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        s.sendall(data)
        data = s.recv(1024)

    print('Received', repr(data))

However, I get a socket error: 但是,我收到一个套接字错误:

socket.error: [Errno 98] Address already in use

What am I doing wrong? 我究竟做错了什么? Will this work or do I need to serialize the JSON object? 这项工作还是需要序列化JSON对象?

There are a few problems with your code, but the one that will likely address your issue is setting the SO_REUSEADDR socket option with: 您的代码存在一些问题,但是可能会解决您问题的一个问题是使用以下命令设置SO_REUSEADDR套接字选项:

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

after you create the socket (with socket.socket(...) but before you attempt to bind to an address (with s.bind() . 在创建套接字之后(使用socket.socket(...)尝试绑定到地址之前(使用s.bind()

In terms of other things, the two "halves" of the code are pretty inconsistent -- like you copied and pasted code from two different places and tried to use them? 在其他方面,代码的两个“一半”是非常不一致的-就像您从两个不同的位置复制并粘贴代码并尝试使用它们一样? (One uses a context manager and Python 3 print syntax while the other uses Python 2 print syntax...) (一个使用上下文管理器和Python 3 print语法,另一个使用Python 2 print语法...)

But I've written enough socket programs that I can decipher pretty much anything, so here's a working version of your code (with some pretty suboptimal parameters eg a buffer size of 1, but how else would you expect to catch a single ; ?) 但是我已经编写了足够的套接字程序,几乎可以解密所有内容,所以这是您的代码的有效版本(带有一些非常次优的参数,例如缓冲区大小为1,但是您还希望捕获单个;吗?)

Server: 服务器:

import socket

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 8192         # The port used by the server
BUFFER_SIZE = 1

def server_socket():
    data = []
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((HOST,PORT))
        s.listen()
        while 1: # Accept connections from multiple clients
            print('Listening for client...')
            conn, addr = s.accept()
            print('Connection address:', addr)
            while 1: # Accept multiple messages from each client
                buffer = conn.recv(BUFFER_SIZE)
                buffer = buffer.decode()
                if buffer == ";":
                    conn.close()
                    print("Received all the data")
                    for x in data:
                        print(x)
                    break
                elif buffer:
                    print("received data: ", buffer)
                    data.append(buffer)
                else:
                    break

server_socket()

Client: 客户:

import socket
import json

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 8192         # The port used by the server

def json_message(direction):
    local_ip = socket.gethostbyname(socket.gethostname())
    data = {
        'sender': local_ip,
        'instruction': direction
    }

    json_data = json.dumps(data, sort_keys=False, indent=2)
    print("data %s" % json_data)

    send_message(json_data + ";")

    return json_data



def send_message(data):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        s.sendall(data.encode())
        data = s.recv(1024)

    print('Received', repr(data))

json_message("SOME_DIRECTION")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM