really stuck finding the problem in my code. A simple server/client program. Have googled the error without any success. Adding the full code just to be sure, although the problem seems to be in the very beginning of the server class.
Output:
Server listening
Client has connected
Exception in thread "Thread-0" java.lang.NullPointerException
at Server.TCPServer.run(TCPServer.java:44)
at java.lang.Thread.run(Thread.java:745)
BUILD STOPPED (total time: 6 seconds)
TCPServer.java
public class TCPServer implements Runnable {
Socket clientSocket;
Boolean connected;
TCPServer(Socket clientScoket, Boolean connected) {
this.clientSocket = clientSocket;
this.connected = connected;
}
public static void main(String args[])
throws Exception {
ServerSocket server = new ServerSocket(1234);
System.out.println("Server listening");
while (true) {
Socket client = server.accept();
System.out.println("Client has connected");
new Thread(new TCPServer(client, true)).start();
}
}
@Override
public void run() {
InputStream clientIn;
try {
clientIn = clientSocket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
OutputStream outToClient = clientSocket.getOutputStream();
PrintWriter pw = new PrintWriter(outToClient, true);
while (true) {
try {
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH) + 1;
year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
String msgFromClient = br.readLine();
System.out.println("Message received from client = " + msgFromClient);
// Send response to the client
//OutputStream clientOut = client.getOutputStream();
//PrintWriter pw = new PrintWriter(clientOut, true);
if ("time".equalsIgnoreCase(msgFromClient)) {
String ansMsg = "Current time is " + hour + " : " + minute + " : " + second;
pw.println(ansMsg);
} else if ("date".equalsIgnoreCase(msgFromClient)) {
String ansMsg = "Current date is " + year + "-" + month + "-" + day;
pw.println(ansMsg);
} else if ((msgFromClient).contains("c2f")) {
String ansMsg = "Temprature in fahrenheit: ";
String[] result = msgFromClient.split(",");
double value = Double.parseDouble(result[1]) * 1.8 + 32;
pw.println(ansMsg + value);
} else if ((msgFromClient).contains("max")) {
double max = 0;
String ansMsg = "Biggest number is: ";
String[] result = msgFromClient.split(",");
for (int counter = 1; counter < result.length; counter++) {
if (Double.parseDouble(result[counter]) > max) {
max = Double.parseDouble(result[counter]);
}
}
pw.println(ansMsg + max);
} else if ((msgFromClient).contains("sum")) {
double sum = 0;
String ansMsg = "The sum of the numbers is: ";
String[] result = msgFromClient.split(",");
for (int counter = 1; counter < result.length; counter++) {
sum = Double.parseDouble(result[counter]) + sum;
}
pw.println(ansMsg + sum);
} else if ((msgFromClient).contains("dload")) {
pw.println(getDload(msgFromClient, outToClient));
}
// Close sockets
if (msgFromClient != null && msgFromClient.equalsIgnoreCase("bye")) {
String response = "Bye!";
System.out.println(response);
pw.println(response);
pw.close();
clientSocket.close();
break;
}
} catch (IOException ie) {
}
}
} catch (IOException ex) {
Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
} finally {
//try {
//clientIn.close();
//} catch (IOException ex) {
///Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
//}
}
}
private OutputStream getDload(String msgFromClient, OutputStream outToClient) throws FileNotFoundException, IOException {
String[] fileName = msgFromClient.split(",");
File myFile = new File("ToSend\\" + fileName[1]);
System.out.println("File exists: " + myFile.exists());
if (!myFile.exists()) {
String response = "Could not find file!";
//pw.println(response);
outToClient.write(response.getBytes("UTF-8"));
} else {
outToClient.write("Incoming File\n".getBytes("UTF-8"));
String fileLength = String.valueOf(myFile.length());
System.out.println("File length in bytes :" + fileLength);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
}
return outToClient;
}
}
TCPClient.java
public class TCPClient {
private final String fileOutput = "C:\\testout.txt";
public static void main(String args[]) {
Socket client = null;
int portnumber = 1234; // Default port number we are going to use
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
byte[] aByte = new byte[1];
int bytesRead;
for (int i = 0; i < 10; i++) {
try {
String msg = "";
// Create a client socket
client = new Socket(InetAddress.getLocalHost(), portnumber);
//System.out.println("Client socket is created " + client);
// Create an output stream of the client socket
BufferedOutputStream clientOut = new BufferedOutputStream(client.getOutputStream());
PrintWriter pw = new PrintWriter(clientOut, true);
// Create an input stream of the client socket
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
// Create BufferedReader for a standard input
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter command. Type Bye to exit. ");
// Read data from standard input device and write it
// to the output stream of the client socket.
msg = stdIn.readLine().trim();
pw.println(msg);
// Stop the operation
if (msg.equalsIgnoreCase("Bye")) {
break;
}
if (msg.contains("dload")) {
//msg.trim();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
String[] fileName = msg.split(",");
long start = System.currentTimeMillis();
File newFile = new File("Received\\" + fileName[1]);
try {
fos = new FileOutputStream(newFile);
bos = new BufferedOutputStream(fos);
bytesRead = clientIn.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = clientIn.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
System.out.println("\nTransfer completed in: " + (System.currentTimeMillis() - start) + " ms.");
} catch (IOException ex) {
ex.printStackTrace();
}
} else {
// Read data from standard input device and write it to the
// output stream of the client socket.
pw.println(msg);
}
// Read data from the input stream of the client socket.
System.out.println("Message returned from the server = " + br.readLine());
pw.close();
br.close();
client.close();
} catch (IOException ie) {
System.out.println("I/O error " + ie);
}
}
}
}