I have created working sockets, and when I try to send text or numbers, its ok, but when im trying to send my custom class object, i got NullPointerException... Here is some cod
Code snippets below works with all kind serializable objects for me. Please check.
*IRequest is object to send. *IResponse is object to get.
Socket clientSocket = new Socket(hostName, portNo);
clientSocket.setSoTimeout(connectionTimeout);
try {
OutputStream outputStream = clientSocket.getOutputStream();
InputStream inputStream = clientSocket.getInputStream();
ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStream);
ObjectInputStream objInputStream = null;
try {
objOutputStream.writeObject(request);
objOutputStream.flush();
objInputStream = new ObjectInputStream(inputStream);
res = (IResponse) objInputStream.readObject();
} finally {
if (objOutputStream != null) {
objOutputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
if (objInputStream != null) {
objInputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
} finally {
clientSocket.close();
clientSocket = null;
}
private IMessageProcessor messageProcessor = null;
private Socket clientSocket = null;
private Logger logger = null;
String clientIP = clientSocket.getInetAddress().getHostAddress();
int clientPortNr = clientSocket.getPort();
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
try {
ObjectInputStream objInputStream = null;
ObjectOutputStream objOutputStream = null;
try {
IRequest request = null;
objInputStream = new ObjectInputStream(inputStream);
objOutputStream = new ObjectOutputStream(outputStream);
request = (IRequest) objInputStream.readObject();
IResponse response = null;
try {
response = messageProcessor.processMessage(clientIP,
clientPortNr,
request,
logger);
objOutputStream.writeObject(response);
} catch (Exception ex) {
objOutputStream.writeObject(ex);
}
objOutputStream.flush();
objOutputStream.reset();
} finally {
if (objInputStream != null)
objInputStream.close();
if (objOutputStream != null)
objOutputStream.close();
}
} finally {
inputStream.close();
outputStream.close();
clientSocket.close();
}
} catch (Exception ex) {
logger.error(ex.getMessage());
}
You need to Serialize your Custom class before sending it through socket.The object that you are sending in
out.writeObject(list);
should be serialized, your class should implement java.io.Serializable interface