im trying to implement a basic chat applcation via sockets but i have problem with ObjectInputStream. Im using both write-read methods in while(true) loop and compiling process got stuck when there is nothing to read and waits for it infinitly. Thus, i need to check wheter is it empty or not before read it.
Here is my codes.
Server:
Socket socket = server.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Server connected!");
oos.flush();
String message = (String) ois.readObject();
System.out.println(ois.available());
txtChat.setText(message);
while(true) {
if(sendMessage) {
oos.writeObject(txtMessage.getText());
oos.flush();
sendMessage = false;
}
while(!sendMessage) {
message = (String) ois.readObject();
txtChat.setText(txtChat.getText()+"\n"+"Client: "+message);
}
Thread.sleep(100);
}
Client:
socket = new Socket(host.getHostName(), 9876);
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
oos.flush();
String message = (String) ois.readObject();
txtChat.setText(message);
while(true) {
message = (String) ois.readObject();
txtChat.setText(txtChat.getText()+"\n"+"Server: "+message);
if(sendMessage) {
oos.writeObject(txtMessage.getText());
oos.flush();
sendMessage = false;
}
Thread.sleep(100);
}