Android Socket没有被实例化

时间:2014-01-24 16:27:15

标签: java android multithreading sockets

我一直在开发一个Android项目,它将连接到另一台计算机上的C#服务器。我用C#客户端测试了服务器端,但是我需要一个Android客户端来连接Android平板电脑。

我发现的问题是套接字没有被实例化,我无法弄清楚原因。任何指导都将不胜感激,我是Android新手,想学习。

首先关闭清单中的权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

接下来在我的.java类中,在触摸事件上调用一个线程:

new Thread(new ClientThread()).start();

最后我们有了主题:

class ClientThread implements Runnable
{
    @Override
    public void run()
    {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
        {
            try
            {
                Log.i("Project", SERVER_IP);
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                Log.i("Project", serverAddr.toString());

                Log.i("Project", String.valueOf(SERVERPORT));                   
                socket = new Socket(serverAddr, SERVERPORT);
                Log.i("Project", "Socket created");

                OutputStream out = socket.getOutputStream();

                Log.i("Project", "Open paint writer");
                PrintWriter output = new PrintWriter(out);

                Log.i("Project", "Sending Data to PC");
                output.println("Hello from Android");

                Log.i("Project", "out.flush");
                out.flush();

                Log.i("Project", "out.close");
                out.close();

                Log.i("Project", "Data sent to PC, close socket");
                socket.close();
            }
            catch (Exception e)
            {
                Log.i("IS4432", "Error");
                e.printStackTrace();
            }
        }
        else
        {
            // display error
            Log.i("Project", "No Internet");
        }

我使用Log来查找代码停止工作的位置,它在socket = new Socket(serverAddr, SERVERPORT);上停止。它也没有任何异常。

编辑 - 解决方案

我按照建议从线程切换到AsyncTask。我实例化了套接字然后连接它。现在我的应用程序能够将字符串发送到服务器

首先从触摸事件中调用该方法:

getSocket task = new getSocket();
task.execute(new String[] { "PlaceHolder" });

方法,我在www.vogella.com上的教程中做了笔记:

private class getSocket extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... urls)
    {
        String response = "";
        String msg = "Hello, from Android<EOF>";
        socket = new Socket();
        Log.i("Project","Socket instantiated");

        try
        {
            socket.connect(new InetSocketAddress(SERVER_IP, SERVERPORT), 5000);
            Log.i("Project","Connection Made");

            // This buffer to receive data from your server  
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            response = in.toString();
            Log.i("Project","Input Stream");

            // This one to send
            OutputStream out = socket.getOutputStream();
            Log.i("Project","Output Stream");

            out.write(msg.getBytes("US-ASCII"));
            out.flush();
            Log.i("Project", msg.getBytes().toString());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("Project","IOException");
        }
        catch (Exception e)
        {
            Log.i("Project","Something went Wrong");
        }
        return response;
    }
}

1 个答案:

答案 0 :(得分:1)

我的建议是,如果你刚刚开始使用Android,请在AsyncTask内实现该套接字。它基本上是一个Thread,如果你使用Thread类,你需要自己控制一些改进。一旦你清楚了解这一点,你可能想要开始体验Thread s,在我看来,开始学习Thread有点'硬核'。

使用以下内容在doInBackground()方法中启动该套接字:

socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);

// This buffer to receive data from your server  
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ISO-8859-1"));
// This one to send
out = socket.getOutputStream();

从服务器读取行:

while ((buffer = in.readLine()) != null) {
  // In my case, buffer is a String
  ...
}

向服务器发送内容:

// The charset is because my server is in spanish :-)
out.write(msg.getBytes("ISO-8859-1"));