I've made one server and client to send data one between another but that don't work and I don't know why...
A little earlier I have that error message from server:
java.net.SocketException: Broken pipe
and now I have null pointer exception from client on line 23:
java.lang.NullPointerException
at chat.Client.sendData(Client.java:23)
Here it's my code:
Server
public class Server {
private ServerSocket server;
public Socket socket;
public Server() {
try {
this.server = new ServerSocket(Port_and_address.PORT);
this.socket = server.accept();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String reciveData() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String result = (String) ois.readObject();
ois.close();
return result;
}
public void writeData(String message) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(message);
oos.close();
}
public void closeSocket() throws IOException {
socket.close();
}
public static void main(String args[]) throws IOException, ClassNotFoundException {
while (true) {
System.out.println("Waiting for client request");
Server server = new Server();
System.out.println(server.reciveData());
server.writeData("TEST SERVER");
server.closeSocket();
}
}
}
Client
public class Client extends Thread {
Socket socket;
public void Client() {
try {
this.socket = new Socket("localhost", Port_and_address.PORT);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendData(String message) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(message);
}
public String reciveData() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ois.close();
return (String) ois.readObject();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Client client = new Client();
client.sendData("TEST CLIENT");
System.out.println(client.reciveData());
}
}
From some reason the that line give null pointer exception:
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
So if anyone of you guys knows what I've do wrong here please tell me. At the end I want to have one server how can receive any message from any client and response on it, theoretical I can have a infinite number of clients how can send messages.
Thx for help :)