gpt4 book ai didi

java - 无法访问 Server 类型的封闭实例

转载 作者:IT老高 更新时间:2023-10-28 21:07:44 25 4
gpt4 key购买 nike

我现在在 Java 中遇到了一个我以前从未见过的奇怪问题。

错误是“没有 Server 类型的封闭实例可访问。必须使用 Server 类型的封闭实例来限定分配(例如 x.new A(),其中 x 是 Server 的实例)。”

我评论的那一行是错误发生的地方。

package game;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

public class Server {

private static List<ThreadModtagClient> clients;

class ReceiveDataListener implements SocketListener {

@Override
public void dataReceived(ThreadModtagClient client, String data) {

}
}

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

clients = new ArrayList<ThreadModtagClient>();

ServerSocket welcomeSocket = new ServerSocket(16567);

while (true) {
Socket connectionSocket = welcomeSocket.accept();

ThreadModtagClient client = new ThreadModtagClient(connectionSocket);
ReceiveDataListener listener = new ReceiveDataListener(); // <--- this is where the error occurs
client.addSocketListener(listener);
clients.add(client);
}

}
}

class ThreadModtagClient extends Thread implements SocketThread {

private BufferedReader inFromClient;
private DataOutputStream outToClient;

private Player player;

private List<SocketListener> listeners;


public ThreadModtagClient(Socket connection) throws IOException {
inFromClient = new BufferedReader(new InputStreamReader(connection.getInputStream()));
outToClient = new DataOutputStream(connection.getOutputStream());
listeners = new ArrayList<SocketListener>();

}

public void addSocketListener(SocketListener listener) {
listeners.add(listener);
}

public void removeSocketListener(SocketListener listener) {
listeners.remove(listener);
}

public Player getPlayer() {
return player;
}

public void setPlayer(Player player) {
this.player = player;
}


public void sendData(String data) throws IOException {
outToClient.writeChars(data);
}

public void run() {

while (true) {
try {

String data = inFromClient.readLine();

for(SocketListener listener : listeners) {
listener.dataReceived(this, data);
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(NoSuchElementException e1) {
e1.printStackTrace();
}
}
}
}

最佳答案

Server.ReceiveDataListener 是一个(非静态)内部类。您正在从静态上下文中创建它。您需要提供一个 Server 实例作为外部实例。但是,几乎可以肯定您希望 ReceiveDataListener 成为静态嵌套类,或者可能是外部类。

关于java - 无法访问 Server 类型的封闭实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7901941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com