0
我最近在玩python,並試圖學習如何使用TCP連接來構建python服務器。Python - 計數服務器從客戶端接收請求的次數?
我有這樣的代碼運行的服務器...
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)
其中兩種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()
我想知道如何讓服務器計算和跟蹤它接收來自客戶端1和客戶端2的消息的次數。
例如,如果服務器從0開始計數(例如,count = 0)
。並且每次客戶端1或客戶端2 se發回一條消息,或者在這種情況下,命中輸入,計數將會增加(count += 1
)。如果我要求print(count)
,則輸出應爲1
。
謝謝?