通过端口3333连接到本地服务器,从服务器接收一行整数,然后查找最大整数数并将该值发送到服务器。我将整数行中的所有值放入一个arraylist中,遍历并找到最大值;但是,当我打印到服务器时,出现BindException且测试失败。
public static void main(String[] args) {
try {
ArrayList<Integer> val = new ArrayList<Integer>();
// contact the server
Socket socket = new Socket("localhost", 3333);
Scanner scanner = new Scanner(socket.getInputStream());
PrintWriter writer = new PrintWriter(socket.getOutputStream(),
true);
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
val.add(num);
}
int max = val.get(0);
for (int i = 1; i < val.size(); i++) {
if (val.get(i) > max) {
max = val.get(i);
}
}
writer.println(max);
scanner.close();
writer.close();
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}