I have a simple example of a socket server where the user connects to it and may or may not immediately send input (in this case it does not). Java throws an exception and I don’t understand why.
Here’s the code:
public static void main(String[] args) {
org.apache.log4j.PropertyConfigurator.configure("conf/log4j.properties");
log.debug("Application started");
try {
// Setup socket server
int port = 9999;
sv = new ServerSocket(port);
// Accept incoming sockets or block
Socket s = sv.accept();
log.warn("Accepted new client connection!");
InputStreamReader reader = new InputStreamReader(s.getInputStream(), "UTF-8");
while(!reader.ready()) {}
char[] b = null;
reader.read(b);
log.warn(new String(b));
} catch (Exception e) {
System.out.print(e.getMessage() + "\n");
e.printStackTrace();
System.exit(1);
}
}
And the stack trace:
DEBUG [main] (Main.java:38) - Application started
WARN [main] (Main.java:47) - Accepted new client connection!
null
java.lang.NullPointerException
at java.io.Reader.read(Reader.java:140)
at com.cinefyapp.Main.main(Main.java:51)
Thanks for helping.
Initialize your char array
and use read(char[] cbuf, int offset, int length).