For educational purposes I tried to make a server and client where the server receives data from multiple clients and echoes each message. The problem is when I try to make the server send the echo to all of the 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 have searched for and answer and saw many similar questions, but none of them helped me. Hope you can point out my mistake. Thanks in advance.
Solution 1 If the non static inner class is modified to the static inner class, the static method will provide access to the static inner class. Changing the non static to the static inner class would fix the exception.
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
Your nested class requires an instance of the outer class, because it's not static - but you don't have an instance of the outer class.
Try making both of your nested classes static
. It doesn't look like they need a reference to the outer class anyway.
In fact, I'd be tempted to avoid using nested classes at all for this - while nested classes can certainly be useful sometimes, they have various corner cases, and it's typically cleaner to create separate top-level types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With