There is no instance of type available ...

For educational purposes, I tried to create a server and a client, where the server receives data from several clients and echoes each message. The problem is that I'm trying to get the server to send an echo to all clients at once.

public class SocketServer { ArrayList<MyRunnable> ts = new ArrayList<MyRunnable>(); ServerSocket serv; static MainServerThread mst = new MainServerThread(); // ^ IDE(eclipse) underlines this as the problem SocketServer() { EventQueue.invokeLater(mst); } public static void main(String[] args) { Thread tr = new Thread(mst); tr.start(); } void send(String s) { for (int i = 0; i < ts.size(); i++) { MyRunnable tmp = ts.get(i); tmp.sendToClient(s); } } class MainServerThread implements Runnable { public void run() { try { serv = new ServerSocket(13131); boolean done = false; while (!done) { Socket s = serv.accept(); MyRunnable r = new MyRunnable(s); Thread t = new Thread(r); ts.add(r); t.start(); } } catch(Exception e) { e.printStackTrace(); } } } class MyRunnable implements Runnable { Socket sock; PrintWriter out; Scanner in; MyRunnable(Socket soc) { sock = soc; } public void run() { try { try { out = new PrintWriter(sock.getOutputStream(), true); in = new Scanner(sock.getInputStream()); boolean done = false; while (!done) { String line = in.nextLine(); send("Echo: " + line); System.out.println("Echo: " + line); if (line.trim().equals("BYE")) done = true; } } finally { sock.close(); } } catch (Exception e) { e.printStackTrace(); } } public void sendToClient(String s) { out.println(s); } } } 

I searched and answered and saw many similar questions, but none of them helped me. Hope you can point out my mistake. Thanks in advance.

+6
source share
1 answer

A nested class requires an instance of an outer class because it is not static, but you do not have an instance of the outer class.

Try to make both of your nested static classes. It looks like they need a reference to an external class.

In fact, I will be tempted to avoid using nested classes at all for this - while nested classes can sometimes be useful sometimes, they have different angular cases, and it is usually cleaner to create separate top-level types.

+14
source

Source: https://habr.com/ru/post/909393/


All Articles