[英]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. 我最近在玩python,并尝试学习如何使用TCP连接来构建python服务器。
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 还有其中两个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. 我想知道如何允许服务器计数并跟踪它从客户端1和客户端2接收到消息的次数。
For example, if server starts at count of 0 (eg count = 0)
. 例如,如果服务器从0开始计数(例如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
). 每次客户端1或客户端2发回一条消息,或者在这种情况下,每次按回车键,计数都会增加( count += 1
)。 If I call for a print(count)
, the output should be 1
. 如果我要求print(count)
,则输出应为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. 我认为您可以在第一个脚本(服务器脚本)中创建一个全局变量(例如count=0
),并在每次从客户端收到消息时保持递增值。
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. 如果您希望计数是特定于客户的,则创建一个计数字典,而不是单个整数,并在验证有关客户机的某些信息时不断增加相应的整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.