无法访问类型为...的封闭实例 [英] No enclosing instance of type ... is accessible
问题描述
出于教育目的,我试图制作一个服务器和一个客户端,其中服务器从多个客户端接收数据并回显每条消息.问题是,当我尝试让服务器一次将回显发送到所有客户端时.
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.
推荐答案
您的嵌套类需要外部类的实例,因为它不是静态的-但是您没有拥有的实例外层阶级.
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.
尝试使两个嵌套类都变为 static
.看起来他们 都不是对外部类的引用.
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.
这篇关于无法访问类型为...的封闭实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!