祝大家好日子。
我正在为我的网吧创建一个java的网络程序。我的服务器代码是
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
public class Server
{
private String name;
private int id;
private Socket socket = null;
private ServerSocket serversocket = null;
private ObjectInputStream ois = null;
public Server()
{
new Thread(receive).start();
while(true)
{
try
{
serversocket = new ServerSocket(4445);
socket = serversocket.accept();
System.out.println("Connected..");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Runnable send = new Runnable(){
public void run ()
{
}
};
Runnable receive = new Runnable(){
public void run ()
{
while(true)
{
try
{
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
User user = (User) ois.readObject();
System.out.println(user);
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
};
public static void main(String [] args)
{
new Server();
}
}
我的问题是我无法在Runnable接口代码中访问我的实例变量。
例如" socket"实例。在此代码中无法访问
Runnable receive = new Runnable(){
public void run ()
{
while(true)
{
try
{
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
User user = (User) ois.readObject();
System.out.println(user);
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
};
这方面的最佳方法是什么?为什么在该代码中无法访问?
答案 0 :(得分:2)
为什么呢?这是答案:Why are only final variables accessible in anonymous class?
如果您需要从服务器访问套接字,则应在Server类上声明最终变量为Socket socket
。
答案 1 :(得分:1)
试试这个
public Server() {
try {
serversocket = new ServerSocket(4445);
while (true) {
socket = serversocket.accept();
new Thread(receive).start();
System.out.println("Connected..");
}
} catch (IOException e) {
e.printStackTrace();
}
}
答案 2 :(得分:1)
如果我没记错,你需要让套接字字段最终。原因让我现在逃脱了。