![](/img/trans.png)
[英]Python freeopcua server: how to know number of connected clients?
[英]How can I know the number of clients connected to the server and return the number of the connected clients to the user?
我想知道這些,因為我對此感到瘋狂:
我該怎么做:
1-如果服務器終止,則客戶端也應終止。 您的服務器應允許管理員關閉所有連接(即,服務器必須等待用戶最好通過菜單界面終止程序)。
2-為了知道連接的客戶端數量,您需要唯一地標識每個客戶端-這可以通過使用為每個客戶端連接唯一分配的pid(將它們存儲在全局列表中)來實現。 這些連接可以動態更改(即客戶端可以斷開連接並重新連接),因此您必須在服務器上維護此列表。 這是我的服務器端代碼:
提前致謝
import _thread
import socket
import sys
from datetime import datetime
def serveclient(c):
global v, nclient, vlock, nclientlock
while(True):
k=(c.recv(1)).decode('utf-8')
if(k==''):
break
if(k=='D'):
today = str(datetime.now().strftime('%Y-%m-%d'))
c.send(today.encode('utf-8'))
if(k=='T'):
tme = str(datetime.now().strftime('%H:%M:%S'))
c.send(tme.encode('utf-8'))
if(k=='X'):
<<<< # Here I should put the number of clients connected and echo back the number like the above code
vlock.acquire()
v+=k
vlock.release()
#Echo back
c.send(v.encode('utf-8'))
c.close() #End connection
nclientlock.acquire()
nclient-=1
nclientlock.release()
#Main driver code
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = int(sys.argv[1])
listener.bind(('',port))
listener.listen(5)
#Initialize global data
v=''
vlock=_thread.allocate_lock()
nclient=10 #Max number of clients
nclientlock=_thread.allocate_lock()
#accept calls from clients
for i in range(nclient):
(client, ap) = listener.accept()
_thread.start_new_thread(serveclient, (client,))
listener.close()
while nclient >0:
pass #do nothing, just wait for client count to drop to zero
print('The final string is: ', v)
<<<<<<<<<<<<<<<<<<<<<<<<<This the Client Code>>>>>>>>>>>>>>>>>>>>>>>
#Client Program. Sends a single char at a time to the server until the client
#sends a '', this will terminate the client.
#
#usage: python server port
import socket
import sys
#create the socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = sys.argv[1] #Server info from cmd line
port = int(sys.argv[2]) #Port from cmd line
#Conncet to server
s.connect((host, port))
while(True):
#get letter
k = input('enter a letter: ')
s.send(k.encode('utf-8'))
if(k==''):
break
v=s.recv(1024) #receive upto 1024 bytes
print(v.decode('utf-8'))
s.close()
只要在每次接受套接字時增加一個計數,就在每次關閉接受的套接字時減少一個計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.