Vì mục đích giáo dục, tôi đã cố gắng tạo một máy chủ và máy khách nơi máy chủ nhận dữ liệu từ nhiều khách hàng và lặp lại từng tin nhắn. Vấn đề là khi tôi cố gắng để làm cho máy chủ gửi echo cho tất cả các khách hàng cùng một lúc.Không có thể hiện kèm theo loại ... có thể truy cập
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);
}
}
}
Tôi đã tìm kiếm và trả lời và thấy nhiều câu hỏi tương tự nhưng không ai trong số họ đã giúp tôi. Hy vọng bạn có thể chỉ ra sai lầm của tôi. Cảm ơn trước.
Có thể trùng lặp của [Java - Không có thể hiện kèm theo loại Foo có thể truy cập được] (http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – Raedwald