Reputation: 1643
this is a simple chat server and client i got from a book i've been reading and I'm having trouble understanding some of the code, can someone please help me with this problem
this is the client code here
public class ChatClient {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String[] args) {
ChatClient client = new ChatClient();
client.go();
}
public void go() {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15, 50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20);
JButton sendButton = new JButton("send");
sendButton.addActionListener(sendButtonListener);
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.add(mainPanel);
frame.setSize(400, 500);
frame.setVisible(true);
}
private void setUpNetworking() {
try {
sock = new Socket("127.0.0.1", 5000);
InputStreamReader streamReader = new InputStreamReader(
sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("connected");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ActionListener sendButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
writer.println(outgoing.getText());
writer.flush();
outgoing.setText("");
outgoing.requestFocus();
}
};
public class IncomingReader implements Runnable {
@Override
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
incoming.append(message + "\n");
}
System.out.println("ggggggggg");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
the part that I'm having trouble understanding is this one:
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
incoming.append(message + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
in this part there is while code that is running as long as what we read from the server is not Null, my questions is won't the first thing that we read from the server as soon as we start the thread would be Null since we haven't written any thing to it yet, thus, breaking out of the loop? like when would message equals Null?
this is the server code to whome ever wants to read it
public class ChatServer {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket) {
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(
sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
tellEveryone(message);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new ChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while (true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(
clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
a way that would be more logical to me would be having a while true loop and checking the server all the time waiting for a message like this:
while(true){
if ((message = reader.readLine()) != null){
System.out.println("read " + message);
incoming.append(message + "\n");
}
}
Upvotes: 0
Views: 51
Reputation: 347184
won't the first thing that we read from the server as soon as we start the thread would be Null since we haven't written any thing to it yet
I think you've answered your own question, in part. null
is returned from BufferedReader#read
when it reaches the EOF, so, since EOF
marker hasn't been reached, the read
method will block until either there is something to be read or EOF
is reached.
From the JavaDocs...
public String readLine()
throws IOException
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns:
A String containing the contents of the line, not including any line-termination > characters, or null if the end of the stream has been reached
The loop is actually infinite. The only way this will break is if the underlying stream is closed, which is likely to cause an IOException
What book did you get this from? It's not a very good example
Upvotes: 1