NullPointerException when receiving an array list over a socket - java

Trying to send an arrayList over a socket, get a null pointer exception at object input stream initialization (client).
Client:
try {
ObjectInputStream objIn = new ObjectInputStream(
Client.socket.getInputStream()); // HERE
library = (ArrayList<Book>) objIn.readObject();
} catch (IOException e) {
Server:
try {
ObjectOutputStream objOut = new ObjectOutputStream(
this.client.getOutputStream());
objOut.writeObject(library);
objOut.flush(); // added later, not helping
}
I've been trying to comunicate over sockets for two days now with almost no success. I have no idea what's going on. Ofc I plan to document myself better when I'll have more time but for now I'd really like to understand what is happening.
EDIT
public class Client {
private static int port = 6666;
private static Socket socket = null;
public Client (int port) {
Client.port = port;
}
public Client () {
}
public void establishConnection() {
try {
Client.socket = new Socket(InetAddress.getByName(null), Client.port);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Server:
public void start () {
(new Thread() {
public void run() {
try {
Server.socket = new ServerSocket(Server.portNumber);
while (!Server.stop) {
Socket client = Server.socket.accept();
(new HandleRequest (client)).start();
}
...............
public class HandleRequest extends Thread {
private Socket client = null;
private SQL sql_db = new SQL ();
public HandleRequest (Socket client) {
this.client = client;
}
#Override
public void run () {
try {
if (!this.sql_db.isConnected())
this.sql_db.connect();
if (this.client == null) {
System.out.println("Error: client does not exist, NO idea what's going on");
return;
}
ArrayList<Book> library = this.sql_db.getAllBooks();
try {
ObjectOutputStream objOut = new ObjectOutputStream(
this.client.getOutputStream());
objOut.writeObject(library);
objOut.flush();
} catch (Exception e) {
System.out.println("Server error in handling request for whole library!");
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Because the NPE is on this line:
Client.socket.getInputStream());
there is only one thing that can cause it. It can't be Client, because that is static. It can't be getInputStream(), because that is a method, so it has to be socket that is causing the NPE.
On this line:
private static Socket socket = null;
you set socket to be null. The only place I see where you set it to be not null is in your .establishConnection() method, but I don't see where you call that method.
Therefore, your problem is most likely that you aren't calling the .establishConnection() method.

Is you establishConnection method called before
try {
ObjectInputStream objIn = new ObjectInputStream(
Client.socket.getInputStream()); // HERE
library = (ArrayList<Book>) objIn.readObject();
} catch (IOException e) {
If not, your Client.socket is null and you need to initialize it. I.e. your code should look like this:
try {
Client c = new Client(1337);
c.establishConnection();
ObjectInputStream objIn = new ObjectInputStream(
c.socket.getInputStream()); // HERE
library = (ArrayList<Book>) objIn.readObject();
} catch (IOException e) {

Related

java client server objects serialization: read objects in the same order they were sent

I'm developing a client server application in java. Communication takes place by serializing/deserializing immuable objects containing the information required, with ObjectOutputStream and ObjectInputStream.
In the server, every time I accept a new tcp connection, I instantiate a new Thread to handle the connection with that particular client.
This thread has a reference to the socket and it keeps reading objects:
while (true){
Object receivedObject = inputStream.readObject();
if (receivedObject instanceof MessageA){
//do sth
} else if (receivedObject instanceof MessageB){
//do sth else
}
this Runnable also has a method to send objects to the client:
public void sendMessage(Message message) {
try {
output.writeObject(message);
output.reset();
} catch (IOException e) {
e.printStackTrace();
}
}
client-side, when the user enters the server's address, I instantiate a SocketClient object to handle the communication with the server:
public class SocketClient extends Observable {
private final Socket socket;
private final ObjectOutputStream outputStream;
private final ObjectInputStream inputStream;
private static int TIMEOUT = 5000;
public SocketClient(String serverAddress, int serverPort) throws IOException {
this.socket = new Socket();
this.socket.connect(new InetSocketAddress(serverAddress, serverPort), TIMEOUT);
this.outputStream = new ObjectOutputStream(socket.getOutputStream());
this.inputStream = new ObjectInputStream(socket.getInputStream());
}
public void readMessage() {
Thread readerThread = new Thread(() -> {
boolean read = true;
while (read) {
Message message;
try {
message = (Message) inputStream.readObject();
notifyObservers(message);
} catch (IOException | ClassNotFoundException e) {
message = new ErrorMessage(null, "Connection lost with the server.");
disconnect();
read = false;
}
}
});
readerThread.start();
}
public void sendMessage(Message message) {
try {
outputStream.writeObject(message);
outputStream.reset();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void disconnect() {
try {
socket.close();
} catch (IOException e) {
// disconnection error
e.printStackTrace();
}
}
}
messages are sent and received in both applications, the only problem is that when I send multiple messages sequentially in the server, they are sometimes received in a different order in the clients.
How may I fix that?

Set server listening a sending messages from (servers/client) to (server/client) separately for each client

Trying to write - distributive simulation framework, where program is represented by an array with moving objects, server send command to move, client answer objects out of array
Goal - server send text message to each connected client separately
- client answer
Problem - can not find a way how to implement server listening and writing to one choosed client
Is there anyone, please, who can help me or get some idea?
private ServerSocket serverSocket;
private ArrayList<BufferedReader> clientBufReaders;
private ArrayList<BufferedWriter> clientBufWriters;
public static void main(String[] args) {
Server server = new Server();
}
public Server() {
try {
this.serverSocket = new ServerSocket(23456);
this.clientBufReaders = new ArrayList<BufferedReader>();
this.clientBufWriters = new ArrayList<BufferedWriter>();
this.clients();
} catch (IOException e) {
e.printStackTrace();
}
}
private void clients() {
Thread acceptThread = new Thread(new Runnable() {
private Scanner in;
public void run() {
while (true) {
try {
Socket clientSocket = serverSocket.accept();
clientBufReaders.add(new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));
clientBufWriters.add(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
this.in = new Scanner(System.in);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
);
acceptThread.start();
while (true) {
synchronized (clientBufReaders) {
for (BufferedReader in : clientBufReaders) {
try {
if (in.ready()) {
System.out.println(in.readLine());
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Separating Client class from JFrame [duplicate]

A few days ago i tried to create a server - client or client Server as an experiment to learn about socket using a thread but then someone told me that i should use swingWorker. I did some research how to use and have implemented it in as practice but it still doesn't work. the swingWorker thread doesn't look like it is running even tho i get a connection and have used .excute(). If you guys can help spot where i am doing wrong that will be great. SwingWorker class is in the startSever() and startClient() method.
private void startServer() {
SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
protected Void doInBackground() {
try {
listeningSocket = new ServerSocket(port);
System.out.println("waiting for connection");
connection = listeningSocket.accept();
connected = true;
System.out.println("Connected");
String incomeMessage =null;
while(connected){
inStream = connection.getInputStream();
inDataStream = new DataInputStream(inStream);
if (myMessage !=null){
outStream = connection.getOutputStream();
outDataStream = new DataOutputStream(outStream);
outDataStream.writeUTF(myMessage);
}
if((incomeMessage = inDataStream.readUTF())!=null){
clientMessage = incomeMessage;
publish(clientMessage);
incomeMessage =null;
}
}
} catch (IOException e) {
clientMessage = "Connection Lost";
}
return null;
}
runningServer.execute();
}
Here's a VERY basic example.
Basically, because you program requires asynchronous communications (that is, you need to be able to read from the socket AND write to it at the same time), you need to offload each stream to a separate thread.
The management process of this example is, well, no existent. Realistically, you should have some kind of "connection" manager that would be able to cleanly close the output and input threads so that, for example, when the user types "bye", the output thread would be able to tell the connection manager that the connection should be terminated. It would then tell the input thread to stop reading any new message and terminate...
Client
public class Client {
public static void main(String[] args) {
try {
Socket master = new Socket("localhost", 8900);
new Thread(new InputHandler(master)).start();
new Thread(new OuputHandler(master)).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static class InputHandler implements Runnable {
private Socket socket;
public InputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (commune) {
String text = reader.readLine();
System.out.println("\n<server> " + text);
if (text.toLowerCase().equals("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
public static class OuputHandler implements Runnable {
private Socket socket;
public OuputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while (commune) {
System.out.print("> ");
String text = scanner.nextLine();
writer.write(text);
writer.newLine();
writer.flush();
if (text.equalsIgnoreCase("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
}
Server
public class Server {
public static void main(String[] args) {
try {
ServerSocket master = new ServerSocket(8900);
Socket socket = master.accept();
new Thread(new InputHandler(socket)).start();
new Thread(new OuputHandler(socket)).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static class InputHandler implements Runnable {
private Socket socket;
public InputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (commune) {
String text = reader.readLine();
System.out.println("\n<client> " + text);
if (text.toLowerCase().equals("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
public static class OuputHandler implements Runnable {
private Socket socket;
public OuputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean commune = true;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);
while (commune) {
System.out.print("> ");
String text = scanner.next();
writer.write(text);
writer.newLine();
writer.flush();
if (text.equalsIgnoreCase("bye")) {
commune = false;
}
}
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
writer.close();
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
}
}
}
Update (whine)
While I have your source code in front of me...
There should very, very, rarely be a need to do textMessage.addKeyListener(this)
Because you are using a JTextField, you should be using a ActionListener instead. There are a a number of important reasons for this, but for you, the main one would be the fact that a "accept" action is Look and Feel dependent. While most systems do use Enter as there "accept" action, is not a guarantee.
Have a look at How to Write a Action Listener for more information
Given the general complexity of what you are trying to do, +1 for a overall good attempt!
Using this example, the following changes work with a single telnet client.
private PrintWriter out;
...
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
myMessage = friendLabel + textMessage.getText();
if (out != null) {
out.println(myMessage);
}
...
}
...
protected Void doInBackground() {
try {
listeningSocket = new ServerSocket(port);
System.out.println("Waiting for connection");
connection = listeningSocket.accept();
connected = true;
System.out.println("Connected");
Scanner in = new Scanner(connection.getInputStream());
out = new PrintWriter(connection.getOutputStream(), true);
publish("Connected");
while (true) {
publish(in.nextLine());
}
} catch (IOException e) {
clientMessage = "Connection Lost";
try {
connection.close();
System.out.println("Closed");
} catch (IOException e1) {
e1.printStackTrace();
connected = false;
}
}
return null;
}
I see your server port is 8900 and your client port is 8900 too. I am not sure if it matters if the server and client are running on the same machine...

Java - client-server clock

I'm kind of stuck on one issue. I got a client-server app in Java, where multiple clients can connect to a server. Now I have a cyclic operation, which is getting the current time (corresponding to my ClockTask on the server side). But I don't really know how do I transmit this time data to all connected clients. It should be done somehow by ObjectOutputStream I guess, but it would be nice if someone could clue me in.
Here's my server code, together with thread running a client connection:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listeningSocket = true;
try {
serverSocket = new ServerSocket(11111);
} catch (IOException e) {
System.err.println("Could not listen on port: 11111");
}
while(listeningSocket){
System.out.println("Waiting for a client to connect...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected!");
ConnectThread ct = new ConnectThread(clientSocket);
ct.start();
}
serverSocket.close();
}
}
Connect thread:
public class ConnectThread extends Thread{
private Socket socket = null;
public ConnectThread(Socket socket) {
super("ConnectThread");
this.socket = socket;
}
#Override
public void run(){
ObjectOutputStream serverOutputStream = null;
ObjectInputStream serverInputStream = null;
try {
System.out.println("check");
serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
System.out.println("check");
serverInputStream = new ObjectInputStream(socket.getInputStream());
serverOutputStream.writeInt(42);
System.out.println("check");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
serverOutputStream.close();
serverInputStream.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and the client:
public class Client {
public static void main(String[] arg) {
Socket socketConnection = null;
ObjectOutputStream clientOutputStream = null;
ObjectInputStream clientInputStream = null;
try {
socketConnection = new Socket("127.0.0.1", 11111);
clientOutputStream = new ObjectOutputStream(
socketConnection.getOutputStream());
clientInputStream = new ObjectInputStream(
socketConnection.getInputStream());
System.out.println("check");
System.out.println(clientInputStream.readInt()); // HERE'S WHERE THE EXCEPTION OCCURS
} catch (Exception e) {
System.out.println("The following exception has occured and was caught:");
System.out.println(e);
}
finally{
try {
clientOutputStream.close();
clientInputStream.close();
socketConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Clock task:
public class ClockTask extends TimerTask {
#Override
public void run() {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Calendar c = Calendar.getInstance();
System.out.println(dateFormat.format(c.getTime()));
//some object output stream here??
}
}
I don't suggest sending a Calendar object as it is a very expensive object using around 2900 bytes. Instead you could send a long value over a DataOutputStream which would use 8 bytes.
Note: you would need to correct for the latency between the client and the server otherwise the time will be always delayed.
A simple way to address this is for the client to send a message to the server with a timestamp as long, the server responds with it's own time stamp and you can assume that the delay is half the round trip time. You can then apply an EWMA (Exponentially Weighted Moving Average) to get a reason average of the difference in the clock on the server and the client.

client/server connection closing causes loop error

I got to stage where client and server communicate, sending messages from and to each other.
The problem I am having is how to close the connection without causing an error?
If I terminate one of the apps (either server or client) that causes the connection to be lost, and then it causes the loop that is waiting for input to loop indefinitely and showing null's.
I tried closing sockets, buffers and even the thread, didn't work.
This is the client side
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
This is the server side
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(
socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Both use these classes:
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(
this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
//***HERE EXTRA BIT FOR THE SERVER
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(msg);
}
}
the only difference is the server has this bit where it says above ***HERE EXTRA BIT FOR THE SERVER
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Message recieved");
so basically, client connects, server accepts, then client sends message, servers receives message and shows it, and then sends "Message received" to the client, and the client shows it.
All this works fine, but once the connection is lost, they hang on showing null repeatedly, and I have to force the app to close.
You aren't checking for end of stream. If readLine() returns null, the peer has closed the connection, and you must do likewise and stop reading.
It's hard to believe you really need a new thread for every line to update the UI.

Categories