用于套接字连接的单例类不起作用

时间:2014-05-08 06:13:26

标签: java android sockets design-patterns singleton

我创建了一个单例类来启用套接字连接,它返回一个套接字对象,可以被应用程序中的任意数量的活动使用。 单例类如下

public class Singleton 
{
private static Socket socket;
private DataInputStream input;
private DataOutputStream output;
private boolean logged;
private static Singleton instance;
private String information;
private static final int SERVERPORT = 8020;
private static final String SERVER_IP = "192.168.1.33";
static PrintWriter out;

private Singleton()
{
}

public static Singleton getInstance()
{
        return instance;
}

public static void initSingleton()
{
    if(instance == null)
    {
        instance = new Singleton();
        InetAddress serverAddr = null;
        try {
            serverAddr = InetAddress.getByName(SERVER_IP);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            socket = new Socket(serverAddr, SERVERPORT);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        try {
            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}



public Socket getSocket()
{
    return socket;
}


public PrintWriter getOutput()
{
    return out;
}

}

在MainActivity中,我调用单例类。

public class MainActivity extends Activity implements OnItemSelectedListener {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     
    initSingleton(); }
protected void initSingleton()
{
    Singleton.initSingleton();
}
public void onClickon(View view) {
    Socket socket = Singleton.getInstance().getSocket();

    try{

        PrintWriter out=Singleton.getInstance().getOutput();    
    out.println("0"); 
    }
    catch (Exception e) {
        e.printStackTrace();
    }

}
  }

按钮单击,调用onClickon函数,该函数使用Singleton类的getSocket()和getOutput()函数返回对象类型。

但应用程序崩溃了。

日志如下。

05-08 11:33:41.236: E/AndroidRuntime(19813): FATAL EXCEPTION: main
05-08 11:33:41.236: E/AndroidRuntime(19813): Process: com.example.clientmobile2, PID: 19813
05-08 11:33:41.236: E/AndroidRuntime(19813): java.lang.RuntimeException: Unable to start activity     ComponentInfo{com.example.clientmobile2/com.example.clientmobile2.MainActivity}: android.os.NetworkOnMainThreadException
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.os.Handler.dispatchMessage(Handler.java:102)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.os.Looper.loop(Looper.java:136)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.app.ActivityThread.main(ActivityThread.java:5102)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at java.lang.reflect.Method.invokeNative(Native Method)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at java.lang.reflect.Method.invoke(Method.java:515)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at dalvik.system.NativeStart.main(Native Method)
05-08 11:33:41.236: E/AndroidRuntime(19813): Caused by: android.os.NetworkOnMainThreadException
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at libcore.io.IoBridge.connect(IoBridge.java:112)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at java.net.Socket.startupSocket(Socket.java:566)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at java.net.Socket.<init>(Socket.java:226)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at com.example.clientmobile2.Singleton.initSingleton(Singleton.java:48)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at com.example.clientmobile2.MainActivity.initSingleton(MainActivity.java:148)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at com.example.clientmobile2.MainActivity.onCreate(MainActivity.java:101)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.app.Activity.performCreate(Activity.java:5248)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
05-08 11:33:41.236: E/AndroidRuntime(19813):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)

4 个答案:

答案 0 :(得分:2)

一个主要的事情是你无法在远程连接等主线程上运行Costly操作.. e.t.c, 我的意思是你为这个套接字连接创建新线程,否则使用异步任务将重新解决你的问题。

注意:请不要忘记关闭连接

答案 1 :(得分:1)

此代码:

protected void initSingleton()
{
    Singleton.initSingleton();
}

在尝试获取实例之前未执行,即使您正在调用该函数onCreate()。为什么要在单独的方法上实例化Singleton而不是在getInstance()中实例化它?

将代码更改为这样,以便在调用Singleton时避免此类问题,并且实例不存在。

public static Singleton getInstance()
{
     if(instance == null)
        initSingleton();

     return instance;
}

private static void initSingleton()
{
     instance = new Singleton();
     InetAddress serverAddr = null;
     try 
     {
         serverAddr = InetAddress.getByName(SERVER_IP);
     } 
     catch (UnknownHostException e) 
     {
         System.err.println("Fail when getting Server Address.");
     }
     try 
     {
         socket = new Socket(serverAddr, SERVERPORT);
     } 
     catch (IOException e) 
     {
         System.err.println("Failed creating new socket.");
     }  
     try 
     {
         out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
     } 
     catch (IOException e) 
     {
          System.err.println("EPIC FAIL HERE"); 
     }
}

主要活动:

public class MainActivity extends Activity implements OnItemSelectedListener 
{
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     
    }

    public void onClickon(View view) 
    {
        Socket socket = Singleton.getInstance().getSocket();
        try
        {
           PrintWriter out=Singleton.getInstance().getOutput();    
           out.println("0"); 
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
  }

答案 2 :(得分:0)

FunctionR的解决方案是正确的,但它不是线程安全的,因此一个解决方案可以是在静态初始化程序中实例化单例变量,或者使用synchronized块来使单例实例化线程安全(http://www.jguru.com/faq/view.jsp?EID=124425)。 / p>

答案 3 :(得分:0)

嗨,我尝试了我们的代码,我做了一些修改,它工作正常,我实例化套接字并在执行中的athead实现initSingleton() MainActivity

&#13;
&#13;
public class ConnectActivity extends Activity {
    Socket clientSocket;
    Singleton instance;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connect);
        instance=new Singleton();

        new Thread(new ClientThread()).start();
        //Socket socket = Singleton.getInstance().getSocket();

    }
    protected void initSingleton()
    {
        instance.initSingleton();
    }
   
    class ClientThread implements Runnable {
        @Override
        public void run() {

                initSingleton();
                Socket socket = Singleton.getInstance().getSocket();
            }
    }
&#13;
&#13;
&#13;

单例()

&#13;
&#13;
public class Singleton {
    public static Socket clientSocket;
    /* private DataInputStream input;
     private DataOutputStream output;*/
    private boolean logged;
    public static Singleton instance;
    public static String information;
    public static int SERVER_PORT;
    public static String SERVER_IP;
    /*static PrintWriter out;*/

    public Singleton() {
    }

    public Singleton(int server_port, String server_ip) {
        SERVER_PORT = server_port;
        SERVER_IP = server_ip;

    }

    public static Singleton getInstance() {
        return instance;
    }

    public static void initSingleton() {
        if (instance == null) {
            instance = new Singleton();
            InetAddress serverAddr = null;
            try {
                serverAddr = InetAddress.getByName(SERVER_IP);
                information=SERVER_IP;
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                clientSocket = new Socket(information, SERVER_PORT);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
    }

    public Socket getSocket() {
        return clientSocket;
    }
}
&#13;
&#13;
&#13;

我将代码更改为我的项目,但我认为您可以使用修改来运行您的“