简体   繁体   中英

Python - counting times a server receives request from client?

I'm playing around with python lately and trying to learn how to build a python server, using TCP connections.

I have this code that runs a server...

import socket
from threading import *
import datetime
import time


serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "localhost"
port = 8000
print (host)
print (port)

serversocket.bind((host, port))

class client(Thread):

    def __init__(self, socket, address):
        Thread.__init__(self)
        self.sock = socket
        self.addr = address
        self.start()


    def run(self):

        while 1:

            st = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
            #cName  =
            print(self.sock.recv(1024).decode()+' sent @ '+ st + ':' , self.sock.recv(1024).decode())

            self.sock.send(b'Processing!')





serversocket.listen(5)
print ('server started and listening')
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

And two of these client.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host ="localhost"
port =8000
cName = 'client 2' # or client 1
s.connect((host,port))

def ts(str):
   s.sendall(cName.encode())
   s.send('e'.encode())
   data = ''
   data = s.recv(1024).decode()
   print (data)

while 2:
   r = input('enter')
   ts(s)

s.close ()

I want to know how to allow the server to count and keep track of how many times it recieves a message from both client 1 and client 2.

For example, if server starts at count of 0 (eg count = 0) . And each time client 1 or client 2 sends back a message or in this case, hits enter, the count will go up ( count += 1 ). If I call for a print(count) , the output should be 1 .

Thanks?

I think you can create a global variable (say count=0 ) in your first script (server script) and keep incrementing the value every time you receive the message from a client.

So your run method can become,

def run(self):
        global count
        while 1:

            st = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
            #cName  =
            print(self.sock.recv(1024).decode()+' sent @ '+ st + ':' , self.sock.recv(1024).decode())
            count += 1
            self.sock.send(b'Processing!')

If you want the count to be client specific then create a dictionary of counts instead of a single integer and keep incrementing the respective integer on verifying some thing about a client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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