gpt4 book ai didi

java - 当我运行客户端-服务器程序时,我得到 ArrayIndexOutofBoundException

转载 作者:行者123 更新时间:2023-12-01 06:07:07 26 4
gpt4 key购买 nike

我正在编写我的第一个java客户端/服务器程序,它只是与服务器建立连接,当我运行程序时,应该打印IP地址和端口号。但是当我运行服务器程序时出现错误。

服务器.java

package serverpro;
import java.io.*;
import java.net.*;

public class Server{
static InetAddress ip;
public static final String HOST="localhost";
public static final int PORT= 4444;


public static void main(String a[]) throws Exception {
System.out.println("starting server..");
System.out.println("Initializing Connection..");

try (
ServerSocket serverSocket = new ServerSocket(PORT);
Socket clientSocket = serverSocket.accept();

//BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
) {
ip = InetAddress.getLocalHost();
System.out.println("InetAdress " + ip.getHostAddress() + " : " + clientSocket.getPort());


} catch (Exception e) {
System.err.println("Exception in starting server: " + e.getMessage());
}
}
}

客户端.java

package serverpro;

import java.io.*;
import java.net.*;

public class Client {
public static void main(String[] args) throws IOException {
try (
Socket client = new Socket(Server.HOST, Server.PORT);
PrintWriter out = new PrintWriter(client.getOutputStream(), true);

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
) {
String inputLine;
while ((inputLine = stdIn.readLine()) != null) {

if ("exit".equals(inputLine)) {
out.println("exit");
break;
}

out.println(inputLine);
out.flush();

final String response = in.readLine();
System.out.println(response);
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}

}}

现在,当我首先运行 ServerProgram 时,我得到以下输出

运行:

Entered server console..
Initializing Connection..

但是当我运行客户端输出时,它显示为 null

运行:

最佳答案

我猜您没有使用任何参数启动程序,因此您的 args 数组为空。使用参数启动程序或找到不同的方法来获取服务器名称和端口。

关于java - 当我运行客户端-服务器程序时,我得到 ArrayIndexOutofBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42061635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com