0

I am having a problem with my code. the code after serverSocket does not work, that means get hanged once it gets to serverSocket.accept.

import java.io.*;
import java.net.*;
public class AppChat {

    String[] list = { 
        "Take me ", 
        "the code", 
        "Hello from the other side", 
        "the man ",
        "what can we do?", 
        "that is all for today" 
        };

    void go() {
        try {
            ServerSocket serverSocket = new ServerSocket(53439);
            boolean t = true;
            while (true) {
                System.out.println("i am about to execute serverSocket");

everything work to this position but after here, this code is stock on .accept. please, what am i doing wrong because I have tried to search for understanding but still not geting the right answer.

                Socket socs = serverSocket.accept();// everything is stocked here
                System.out.println("unfortunatly the serverSocket.accept is hoding all the goodies");
                PrintWriter wr = new PrintWriter(socs.getOutputStream());
                String advce = getAdvice();
                wr.println(advce);
                wr.close();
                System.out.println(advce);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getAdvice() {
        int randdon = (int) (Math.random() * list.length);
        // System.out.println(list[randdon]);
        return list[randdon];
    }

    public static void main(String[] args) {
        AppChat app = new AppChat();
        app.go();
        app.getAdvice();
    }
}
Matt Fletcher
  • 8,182
  • 8
  • 41
  • 60

1 Answers1

1

ServerSocket#accept() blocks until it gets an incoming connection from a client. If no client connects, this line will block infinitely.

Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72