我在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,依此类推。提前谢谢。
答案 0 :(得分:0)
创建一个arrayList
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
}
答案 1 :(得分:0)
正如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
}
}
我还建议您保留一系列连接,这样就不会丢失它们。