[英]Java connection pool is not limiting the number of TCP connections opened to the DB server
[英]Limiting the number of connections to a server
我有一個使用Java的多線程服務器,但是我想將連接的客戶端數限制為2。這是一個基本應用程序,僅用於測試。
在我的服務器上,我有一個int userNo屬性,該屬性為客戶端分配0或1的值。
我的問題是,是否有更好的方法來處理此問題。 我最多只希望連接2個客戶端,我希望我的應用程序忽略其他任何請求。
偽代碼:
if(userNo == 0) {
this is player 1;
}
if (userNo == 1) {
this is player 2;
}
else {
do nothing
}
我會做這樣的事情:
int connectedClientCount = 0;
// ...
while(true) {
ServerSocket ss = ...
Socket s = ss.accept();
if(connectedClientCount == 2) {
// Do stuff to tell connected Client that he is rejected because of max clients...
} else {
connectedClientCount++;
// cool stuff...
}
}
和您代碼中的其他位置(在客戶端斷開連接時執行)
public void clientDisconnected() {
connectedClientCount--;
}
由於簡單起見,在此示例中,我不使用線程同步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.