-2

I want to store all the messages from clients in a list on my 'TCP server'.

import SocketServer

class MainServerHandler(SocketServer.BaseRequestHandler):
    requests = []

    def handle(self):
            message = self.request.recv(4)
            self.requests.append(message)


HOST, PORT = "localhost", 9999
server = SocketServer.TCPServer((HOST, PORT), MainServerHandler)
server.serve_forever()

When server receives the first message, the handle function appends the message to list.

When server receives the second message from client, there is no trace of the previously appended message.

DISCLAIMER : I know why this is happening. I am just not able to figure out a way to store all the messages in a list. I only want to use SocketServer to implement this.

jwpfox
  • 5,124
  • 11
  • 45
  • 42
kartik
  • 55
  • 4
  • Why is it happening? –  Nov 04 '17 at 06:08
  • I just tested your code by running it and then doing `echo -e abcd | nc localhost 9999` multiple times and each new message gets appended to `requests`. –  Nov 04 '17 at 06:26
  • Your code works, as demonstrated in my answer below. If what you have isn't working, it is in code you haven't shown. Make a [mcve]. – Mark Tolonen Nov 04 '17 at 06:35

1 Answers1

0

The request handler gets a new instance for each client connection, but you've created requests as a class variable so it works:

#!python2
import SocketServer

class MainServerHandler(SocketServer.BaseRequestHandler):
    requests = []
    def handle(self):
            message = self.request.recv(4)
            self.requests.append(message)
            print(self.requests)

HOST, PORT = "", 9999
server = SocketServer.TCPServer((HOST, PORT), MainServerHandler)
server.serve_forever()

client:

import socket

for i in range(3):
    s = socket.socket()
    s.connect(('localhost',9999))
    s.sendall(b'abc')
    s.close()

Output from server:

[b'abc']
[b'abc', b'abc']
[b'abc', b'abc', b'abc']
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251