Create individual names for multiple sockets in python in order to save data received to different files

huangapple go评论71阅读模式
英文:

Create individual names for multiple sockets in python in order to save data received to different files

问题

我目前已经创建了一段代码,用于创建具有不同端口的多个套接字。每个端口将从客户端接收数据并将其保存到不同的文件进行分析。我想要为每个连接命名一个唯一的名称,以确保数据保存到正确的文件。或者是否有一种方法可以检查数据正在接收的端口并根据端口保存数据?由于数据将同时进入,因此确保数据进入正确的文件非常重要。所有客户端都来自本地主机,因此检查地址将没有帮助。

我已经尝试找到一种检查数据来自哪个端口的方法,但我无法解决这个问题。我不能只是检查当前连接的端口,因为列表中的所有端口都将同时连接。我正在使用Python 3.10.9。

import select
import socket
import root_directory
from Account import Symbols

s = Symbols.Symbols()
symbol_total = len(s.Symbol())
ports_list = [*range(9000, (symbol_total + 9000), 1)]

def make_socket(number):
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  sock.bind(('', number))
  sock.listen(5)
  return sock

read_list = list(map(lambda x: make_socket(x), ports_list))

notAccepted = read_list[:]

while True:
    readable, writable, errored = select.select(read_list, [], [])
    for s in readable:
        if s in notAccepted:
            client_socket, address = s.accept()
            read_list.append(client_socket)
        else:
            data = client_socket.recv(1000000)
            cummdata = ''
            cummdata = data.decode("utf-8")
            print(s)
            if data:
                pass
            else:
                s.close()
                read_list.remove(s)

希望这有所帮助!

英文:

I currently have created a code that creates multiple sockets with different ports. Each port will receive data from the client side and save them to different files for analysis. I would like to name each connection something unique to ensure that the data is saved to the right file. Or is there a way for me to check what port the data is being received on and save it based on the port? The data will come in at the same time so ensuring the data is going to the correct file is critical. All the clients are coming from the localhost so checking address won't be helpful.

I have tried to find a way to check for which port the data is coming from but I can't figure that out. I can't just check which port is currently connected as all the ports in the list will be connected at once. I'm using python 3.10.9.

Kind Regards


import select
import socket
import root_directory
from Account import Symbols

s = Symbols.Symbols()
symbol_total = len(s.Symbol())
ports_list=[*range(9000, (symbol_total + 9000), 1)]

def make_socket(number):
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  sock.bind(('', number))
  sock.listen(5)
  return sock

read_list= list(map(lambda x: make_socket(x), ports_list))

notAccepted = read_list[:]

while True:
    readable, writable, errored = select.select(read_list, [], [])
    for s in readable:
        if s in notAccepted:
            client_socket, address = s.accept()
            read_list.append(client_socket)
        else:
            data = client_socket.recv(1000000)
            cummdata = ''
            cummdata = data.decode("utf-8")
            print(s)
            if data:
                pass
            else:
                s.close()
                read_list.remove(s)

答案1

得分: 1

socket.getpeername() 检索套接字的远程端的地址/端口。

socket.getsockname() 检索套接字的本地端的地址/端口。

此外,socket.makefile() 将套接字包装成一个类似文件的对象,以便缓冲接收数据,直到你拥有完整的消息,例如下面示例中的完整以换行终止的文本消息。请注意,.recv(n) 可以接收 1 到 n 字节的数据,你不能假设在 TCP 中已经有完整的消息,因为它不是基于消息的协议,而是一种流式协议。

英文:

socket.getpeername() retrieves the address/port of the remote end of the socket.

socket.getsockname() retrieves the address/port of the local end of the socket.

Also, socket.makefile() wraps a socket in a file-like object so your receives are buffered until you have a complete message, such as a complete newline-terminated text message as in my example below. Note that .recv(n) can receive 1-n bytes of data and you can't assume you have a complete message in TCP, which isn't message-based. It is a streaming protocol.

server.py

import select
import socket

BASE = 9000
SOCKS = 5

servers = []
for port in range(BASE, BASE+SOCKS):
    sock = socket.socket()
    sock.bind(('', port))
    sock.listen()
    servers.append(sock)

read_list = {s:None for s in servers}

while True:
    readable, writable, errored = select.select(read_list, [], [])
    for s in readable:
        if s in servers:
            client_socket, address = s.accept()
            client = client_socket.makefile('r', encoding='utf8')
            server_port = client_socket.getsockname()[1]
            client_port = address[1]
            # For clients, store the ports and makefile wrapper
            # for later lookup in the dictionary.
            # You could store the "name" of the port or log file here.
            read_list[client_socket] = server_port, client_port, client
            print(f'{client_port}->{server_port}: CONNECTED')
        else:
            server_port, client_port, client = read_list
展开收缩
data = client.readline() if data: print(f'{client_port}->{server_port}: {data}', end='') else: print(f'{client_port}->{server_port}: DISCONNECTED') del read_list
展开收缩
s.close() client.close()

client.py

import socket

SOCKS = 5
BASE = 9000

socks = [socket.socket() for _ in range(SOCKS)]
for port, s in enumerate(socks, BASE):
    s.connect(('localhost', port))
for s in socks:
    for i in range(1,3):
        s.sendall(f'message {i} on port {s.getsockname()[1]} to port {s.getpeername()[1]}\n'.encode())
for s in socks:
    s.close()

Server output:

30107->9000: CONNECTED
30108->9001: CONNECTED
30109->9002: CONNECTED
30110->9003: CONNECTED
30111->9004: CONNECTED
30107->9000: message 1 on port 30107 to port 9000
30108->9001: message 1 on port 30108 to port 9001
30109->9002: message 1 on port 30109 to port 9002
30110->9003: message 1 on port 30110 to port 9003
30111->9004: message 1 on port 30111 to port 9004
30107->9000: message 2 on port 30107 to port 9000
30108->9001: message 2 on port 30108 to port 9001
30109->9002: message 2 on port 30109 to port 9002
30110->9003: message 2 on port 30110 to port 9003
30111->9004: message 2 on port 30111 to port 9004
30107->9000: DISCONNECTED
30108->9001: DISCONNECTED
30109->9002: DISCONNECTED
30110->9003: DISCONNECTED
30111->9004: DISCONNECTED

huangapple
  • 本文由 发表于 2023年3月8日 18:51:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75672076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定