So I have this little code:
public class MyCounterClass {
private static int counter = 0;
synchronized public static int getCounter(){
return counter++;
}
}
This is the server:
public class MyServer implements Runnable{
public static void go() throws IOException {
System.out.println("MyServer: Go called...");
ServerSocket serverSocket = new ServerSocket(5000);
while(true){
Socket socket = serverSocket.accept();
System.out.println(time() + "MyServer: Connection accepted!");
OutputStream outputStream = socket.getOutputStream();
System.out.println(time() + "MyServer: socket.getOutputStream");
PrintWriter printWriter = new PrintWriter(outputStream);
System.out.println(time() + "MyServer: New PrintWriter object created!");
printWriter.write(time() + "Hello from my socket!");
System.out.println(time() + "MyServer: printwriter.write method called..");
printWriter.flush();
System.out.println(time() + "MyServer: Flushed!");
printWriter.close();
System.out.println(time() + "MyServer: printWriter closed...");
}
}
public static String time(){
return String.valueOf(MyCounterClass.getCounter()) + " ";
}
@Override
public void run() {
try {
go();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is the Client:
public class MyClient implements Runnable {
public static void go() throws IOException {
Socket socket = new Socket("localhost",5000);
System.out.println(time() + "My Client: Connection established...");
InputStream inputStream = socket.getInputStream();
System.out.println(time() + "MyClient: socket.getInputStream...");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
System.out.println(time() + "MyClient: BufferedReader object created...");
System.out.println(time() + bufferedReader.readLine());
}
public static String time(){
return String.valueOf(MyCounterClass.getCounter()) + " ";
}
@Override
public void run() {
try {
go();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And how I run the program:
public class TestClass {
public static void main(String[] args) throws IOException, InterruptedException {
Thread server = new Thread(new MyServer());
server.start();
Thread.sleep(750);
Thread client = new Thread(new MyClient());
client.start();
}
}
And the output:
MyServer: Go called...
0 My Client: Connection established...
1 MyServer: Connection accepted!
2 MyClient: socket.getInputStream...
3 MyServer: socket.getOutputStream
4 MyClient: BufferedReader object created...
6 MyServer: New PrintWriter object created!
8 MyServer: printwriter.write method called..
9 MyServer: Flushed!
10 MyServer: printWriter closed...
5 7 Hello from my socket!
My question is, how can the last line get "5 and 7"?