Dheeraj Joshi Dheeraj Joshi - 3 years ago 194
Java Question

how java SocketServer works?

I am new to java, I can't understand the while loop part of void go() method.The accept() method waits for the client request to connect to the server, so why the other statements like Print writer etc, are not executed?

Do the other statments wait in the while loop for the accept() methods to run??

import java.io.*;
import java.net.*;
import java.util.*;

public class VerySimpleChatServer
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);
} catch (Exception ex) { ex.printStackTrace(); }

public static void main(String[] args) {
new VerySimpleChatServer().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());

Thread t = new Thread(new ClientHandler(clientSocket));
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();
} catch (Exception ex) { ex.printStackTrace(); }

No clue, please help

Answer Source

That accept method does not just wait.

It blocks. Execution only continues when that method returns! The "flow of execution" stops there - the following statements are irrelevant until that method call returns.

That is all there is to this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download