I have a simple server to client program that lets the server send text to the clients, There is no connection problems. However, I'm not sure what to put the while loop which updates the JLabel
of the sent text. If I put while(true)
I get an error saying no lines found.
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Client {
private static JLabel l = new JLabel();
public Client() {
JFrame f = new JFrame("Client");
JPanel p = new JPanel(null);
f.setSize(300, 150);
f.setLocationRelativeTo(null);
l.setSize(300, 20);
l.setLocation(0, 65);
p.add(l);
f.add(p);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) throws IOException {
new Client();
Socket socket = new Socket("localhost", 12000);
Scanner in = new Scanner(socket.getInputStream());
while(/* code goes here */) {
l.setText(in.nextLine());
}
}
}
private class PollingThread implements Runnable {
public void run() {
while (true) {
try {
l.setText(in.nextLine());
} catch (/* */) {
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Log.d(TAG, "Thread interrupted");
}
}
}
Create a private nested class inside Client class.
Initiate the thread from Client class's main() method.
PollingThread mPollingThread = new PollingThread();
mPollingThread.start();