JAVA 如何循环套接字变量

JAVA How to Loop Socket Variable

我正在 java 中创建一个简单的客户端服务器程序。

我想做的是迭代变量,这样我就可以缩短我的代码。在这里。

             Socket b1 = ss.accept();
             Socket b2 = ss.accept();
             Socket b3 = ss.accept();
        if(b1.isConnected()){
             System.out.println("Player from " + (b1.getLocalAddress().toString().substring(1) + ":" + b1.getLocalPort() + " has joined."));
        }

        DataOutputStream b1o = new DataOutputStream(b1.getOutputStream());
        BufferedReader b1i = new BufferedReader( new InputStreamReader (b1.getInputStream()));

        if(b2.isConnected()){
             System.out.println("Player from " + (b2.getLocalAddress().toString().substring(1) + ":" + b2.getLocalPort() + " has joined."));
        }

        DataOutputStream b2o = new DataOutputStream(b2.getOutputStream());
        BufferedReader b2i = new BufferedReader( new InputStreamReader (b.getInputStream()));

        if(b3.isConnected()){
        System.out.println("Player from " + (b3.getLocalAddress().toString().substring(1) + ":" + b3.getLocalPort() + " has joined."));
        }

        DataOutputStream b3o = new DataOutputStream(b3.getOutputStream());
        BufferedReader b3i = new BufferedReader( new InputStreamReader (b3.getInputStream()));

有什么方法可以循环变量名,使其在第一个循环中进入 b1,然后进入 b2,依此类推。提前致谢。

创建数组列表

ArrayList<Socket> socketList = new ArrayList();
socketList.add(ss.accept());
socketList.add(ss.accept());
socketList.add(ss.accept());

然后遍历 socketList

for(Socket socket : socketList){
  //Add your code here
 }

正如 MadProgrammer 所说,最好在每个连接上启动一个新线程,因为 ss.accept() 块。你可以尝试这样的事情:

Socket b;
ServerSocket ss;
ClientConnection newClient;
Thread newThread;

while(true) {
    try {
        b = ss.accept();

        System.out.println("Player from " + (b.getLocalAddress().toString().substring(1) + ":" + b.getLocalPort() + " has joined."));
        newClient = new ClientConnection(b);

        newThread = new Thread(newClient);
        newThread.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

class ClientConnection implements Runnable {

    //each connection should have its own socket and streams
    private Socket socket;
    private ObjectOutputStream outputStream;
    private ObjectInputStream inputStream;

    public ClientConnection(Socket socket) {
       this.socket = socket;
       this.outputStream = new ObjectOutputStream(socket.getOutputStream());
       this.inputStream = new ObjectInputStream(socket.getInputStream());
    }

    @Override
    public void run() {
        //do stuff with connection you have
    }
}

我还建议保留一组连接,以免丢失它们。