I have a problem with my Java program. I have this codes:
Host.java:
public class Host {
protected static void start(JFrame window) {
ServerSocket server = null;
try {
server = new ServerSocket();
SocketAddress addr = new InetSocketAddress(hostname, port);
server.bind(addr);
Socket socket = server.accept();
window.setVisible(false);
Thread thread = new Thread(new Incomming(socket.getInputStream()));
thread.start();
thread.join();
socket.close();
} catch (UnknownHostException e) {
[...]
}
}
Incomming.java:
public class Incomming implements Runnable {
private DataInputStream is;
public Incomming(InputStream is) {
MyFrame frame = new MyFrame();
frame.setVisible(true);
frame.pack();
this.is = new DataInputStream(is);
}
public void run() {
try {
while(!Thread.currentThread().isInterrupted()) {
int n = is.readInt();
if(n == -1) {
break;
}
byte[] b = new byte[n];
is.readFully(b);
[...] // working with bytes
}
System.out.println("Stream closed.");
} catch(IOException e) {
[...]
}
}
}
Client.java is very similar to Host.java, it uses Incomming.java for socket.getInputStream() too.
So the problem is: the client connects to the host, but when it should show on server side and also on client side the MyFrame window, it doesn't load it fully. And the close button of old JFrame windows (on both sides) doesn't do anything.
I tried to remove the line with thread.join()
, and then the MyFrame window loads completely and close buttons work, but it throws me exception with socket closed
message, so the client is no longer connected to the host.
How could I fix this problem? Thanks for replies.