Hello, please tell me the sockets. There is a code:
import java.io.*; import java.net.*; public class DailyAdviceServer { String[] adviceList = {"Ешьте меньшими порциями", "Купите облегающие джинсы. Нет, они сделают вас " + "полнее.", "Два слова: не годится", "Будьте честны хотя бы сегодня. Скажите своему " + "начальнику все, что вы *на самом деле* о нем думаете.", "Возможно, вам " + "стоит подобрать другую прическу."}; public void go() { try { ServerSocket serverSock = new ServerSocket(4242); while(true) { Socket sock = serverSock.accept(); PrintWriter writer = new PrintWriter(sock.getOutputStream()); String advice = getAdvice(); writer.println(advice); writer.close(); System.out.println(advice); } } catch(IOException e) { e.printStackTrace(); } } private String getAdvice() { int random = (int)(Math.random() * adviceList.length); return adviceList[random]; } public static void main(String[] args) { DailyAdviceServer server = new DailyAdviceServer(); server.go(); } } Interested in this fragment:
try { ServerSocket serverSock = new ServerSocket(4242); while(true) { Socket sock = serverSock.accept(); PrintWriter writer = new PrintWriter(sock.getOutputStream()); String advice = getAdvice(); writer.println(advice); writer.close(); System.out.println(advice); } } catch(IOException e) { e.printStackTrace(); } Here a server socket is created, a port is assigned. But I can’t understand how the accept() method works. As I understand it, it is waiting for the connection from the client. Those. if the client has not initiated the connection, these lines are not executed?
PrintWriter writer = new PrintWriter(sock.getOutputStream()); String advice = getAdvice(); writer.println(advice); writer.close(); System.out.println(advice);