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

时间:2018-11-17 05:06:34

标签: python json sockets tcp

我在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()

我正在尝试将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))

但是,我收到一个套接字错误:

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

我在做什么错?这项工作还是需要序列化JSON对象?

1 个答案:

答案 0 :(得分:1)

您的代码有一些问题,但是可能会解决您问题的一个问题是使用以下命令设置SO_REUSEADDR套接字选项:

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

在创建套接字后(使用socket.socket(...),但在之前尝试绑定到地址(使用s.bind()

在其他方面,代码的两个“一半”是非常不一致的-就像您是从两个不同的地方复制并粘贴代码并尝试使用它们一样?  (一个使用上下文管理器和Python 3 print语法,另一个使用Python 2 print语法...)

但是我已经编写了足够的套接字程序,几乎可以解密所有内容,所以这是您的代码的有效版本(带有一些非常次优的参数,例如缓冲区大小为1,但是您还希望如何捕获单个代码? ;?)

服务器:

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()

客户

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")