示例:使用AsyncTask的Android双向网络套接字

示例:使用AsyncTask的Android双向网络套接字,android,android-asynctask,android-networking,Android,Android Asynctask,Android Networking,我为Android找到的大多数网络套接字示例都是单向的。我需要一个双向数据流的解决方案。我终于了解了这个任务。此示例演示如何从套接字获取数据并将数据发送回套接字。由于接收数据的套接字的阻塞性质,该阻塞需要在UI线程以外的线程中运行 为了举例说明,此代码连接到Web服务器。按下“启动异步任务”按钮将打开套接字。套接字打开后,web服务器将等待请求。按下“发送消息”按钮将向服务器发送请求。来自服务器的任何响应都将显示在TextView中。对于http,一旦发送了所有数据,web服务器就会断开与客户端

我为Android找到的大多数网络套接字示例都是单向的。我需要一个双向数据流的解决方案。我终于了解了这个任务。此示例演示如何从套接字获取数据并将数据发送回套接字。由于接收数据的套接字的阻塞性质,该阻塞需要在UI线程以外的线程中运行

为了举例说明,此代码连接到Web服务器。按下“启动异步任务”按钮将打开套接字。套接字打开后,web服务器将等待请求。按下“发送消息”按钮将向服务器发送请求。来自服务器的任何响应都将显示在TextView中。对于http,一旦发送了所有数据,web服务器就会断开与客户端的连接。对于其他TCP数据流,连接将一直保持,直到一侧断开连接

截图:

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.exampleasynctask"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

res\layout\main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button android:id="@+id/btnStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start AsyncTask"></Button>
<Button android:id="@+id/btnSend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send Message"></Button>
<TextView android:id="@+id/textStatus" android:textSize="24sp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Status Goes Here" />
</LinearLayout>

src\com.exampleAyncTask\MainActivity.java:

package com.exampleasynctask;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button btnStart, btnSend;
    TextView textStatus;
    NetworkTask networktask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStart = (Button)findViewById(R.id.btnStart);
        btnSend = (Button)findViewById(R.id.btnSend);
        textStatus = (TextView)findViewById(R.id.textStatus);
        btnStart.setOnClickListener(btnStartListener);
        btnSend.setOnClickListener(btnSendListener);
        networktask = new NetworkTask(); //Create initial instance so SendDataToNetwork doesn't throw an error.
    }

    private OnClickListener btnStartListener = new OnClickListener() {
        public void onClick(View v){
            btnStart.setVisibility(View.INVISIBLE);
            networktask = new NetworkTask(); //New instance of NetworkTask
            networktask.execute();
        }
    };
    private OnClickListener btnSendListener = new OnClickListener() {
        public void onClick(View v){
            textStatus.setText("Sending Message to AsyncTask.");
            networktask.SendDataToNetwork("GET / HTTP/1.1\r\n\r\n");
        }
    };

    public class NetworkTask extends AsyncTask<Void, byte[], Boolean> {
        Socket nsocket; //Network Socket
        InputStream nis; //Network Input Stream
        OutputStream nos; //Network Output Stream

        @Override
        protected void onPreExecute() {
            Log.i("AsyncTask", "onPreExecute");
        }

        @Override
        protected Boolean doInBackground(Void... params) { //This runs on a different thread
            boolean result = false;
            try {
                Log.i("AsyncTask", "doInBackground: Creating socket");
                SocketAddress sockaddr = new InetSocketAddress("192.168.1.1", 80);
                nsocket = new Socket();
                nsocket.connect(sockaddr, 5000); //10 second connection timeout
                if (nsocket.isConnected()) { 
                    nis = nsocket.getInputStream();
                    nos = nsocket.getOutputStream();
                    Log.i("AsyncTask", "doInBackground: Socket created, streams assigned");
                    Log.i("AsyncTask", "doInBackground: Waiting for inital data...");
                    byte[] buffer = new byte[4096];
                    int read = nis.read(buffer, 0, 4096); //This is blocking
                    while(read != -1){
                        byte[] tempdata = new byte[read];
                        System.arraycopy(buffer, 0, tempdata, 0, read);
                        publishProgress(tempdata);
                        Log.i("AsyncTask", "doInBackground: Got some data");
                        read = nis.read(buffer, 0, 4096); //This is blocking
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.i("AsyncTask", "doInBackground: IOException");
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("AsyncTask", "doInBackground: Exception");
                result = true;
            } finally {
                try {
                    nis.close();
                    nos.close();
                    nsocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Log.i("AsyncTask", "doInBackground: Finished");
            }
            return result;
        }

        public void SendDataToNetwork(String cmd) { //You run this from the main thread.
            try {
                if (nsocket.isConnected()) {
                    Log.i("AsyncTask", "SendDataToNetwork: Writing received message to socket");
                    nos.write(cmd.getBytes());
                } else {
                    Log.i("AsyncTask", "SendDataToNetwork: Cannot send message. Socket is closed");
                }
            } catch (Exception e) {
                Log.i("AsyncTask", "SendDataToNetwork: Message send failed. Caught an exception");
            }
        }

        @Override
        protected void onProgressUpdate(byte[]... values) {
            if (values.length > 0) {
                Log.i("AsyncTask", "onProgressUpdate: " + values[0].length + " bytes received.");
                textStatus.setText(new String(values[0]));
            }
        }
        @Override
        protected void onCancelled() {
            Log.i("AsyncTask", "Cancelled.");
            btnStart.setVisibility(View.VISIBLE);
        }
        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                Log.i("AsyncTask", "onPostExecute: Completed with an Error.");
                textStatus.setText("There was a connection error.");
            } else {
                Log.i("AsyncTask", "onPostExecute: Completed.");
            }
            btnStart.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        networktask.cancel(true); //In case the task is currently running
    }
}
package com.exampleAyncTask;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.net.InetSocketAddress;
导入java.net.Socket;
导入java.net.SocketAddress;
导入android.app.Activity;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.TextView;
公共类MainActivity扩展了活动{
按钮btnStart,btnSend;
文本查看文本状态;
网络任务;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnStart=(按钮)findViewById(R.id.btnStart);
btnSend=(按钮)findviewbyd(R.id.btnSend);
textStatus=(TextView)findViewById(R.id.textStatus);
btnStart.setOnClickListener(btnStartListener);
setOnClickListener(btnSendListener);
networktask=new networktask();//创建初始实例,使SendDataToNetwork不会引发错误。
}
私有OnClickListener btnStartListener=新OnClickListener(){
公共void onClick(视图v){
btnStart.setVisibility(视图不可见);
networktask=newnetworktask();//networktask的新实例
networktask.execute();
}
};
私有OnClickListener btnSendListener=新OnClickListener(){
公共void onClick(视图v){
setText(“向异步任务发送消息”);
networktask.SendDataToNetwork(“GET/HTTP/1.1\r\n\r\n”);
}
};
公共类NetworkTask扩展了AsyncTask{
套接字nsocket;//网络套接字
InputStream nis;//网络输入流
OutputStream nos;//网络输出流
@凌驾
受保护的void onPreExecute(){
Log.i(“AsyncTask”、“onPreExecute”);
}
@凌驾
受保护的布尔doInBackground(Void…params){//此操作在不同的线程上运行
布尔结果=假;
试一试{
i(“AsyncTask”、“doInBackground:创建套接字”);
SocketAddress sockaddr=新的InetSocketAddress(“192.168.1.1”,80);
nsocket=新套接字();
nsocket.connect(sockaddr,5000);//连接超时10秒
如果(nsocket.isConnected()){
nis=nsocket.getInputStream();
nos=nsocket.getOutputStream();
i(“AsyncTask”,“doInBackground:创建套接字,分配流”);
i(“AsyncTask”,“doInBackground:等待初始数据…”);
字节[]缓冲区=新字节[4096];
int read=nis.read(缓冲区,04096);//这是阻塞
while(读取!=-1){
字节[]临时数据=新字节[读取];
数组复制(缓冲区,0,tempdata,0,读取);
出版进度(临时数据);
i(“AsyncTask”,“doInBackground:获得一些数据”);
read=nis.read(缓冲区,04096);//这是阻塞
}
}
}捕获(IOE异常){
e、 printStackTrace();
Log.i(“AsyncTask”、“doInBackground:IOException”);
结果=真;
}捕获(例外e){
e、 printStackTrace();
i(“AsyncTask”、“doInBackground:Exception”);
结果=真;
}最后{
试一试{
nis.close();
关闭次数();
nsocket.close();
}捕获(IOE异常){
e、 printStackTrace();
}捕获(例外e){
e、 printStackTrace();
}
Log.i(“AsyncTask”、“doInBackground:Finished”);
}
返回结果;
}
public void SendDataToNetwork(String cmd){//您可以从主线程运行它。
试一试{
如果(nsocket.isConnected()){
i(“AsyncTask”,“SendDataToNetwork:将收到的消息写入套接字”);
nos.write(cmd.getBytes());
}否则{
Log.i(“AsyncTask”,“SendDataToNetwork:无法发送消息。套接字已关闭”);
}
}捕获(例外e){
Log.i(“AsyncTask”、“SendDataToNetwork:消息发送失败。捕获到异常”);
}
}
@凌驾
受保护的void onProgressUpdate(字节[]…值){
如果(value.length>
public boolean sendDataToNetwork(final byte[] cmd) { 
    if (_nsocket.isConnected()) {
        Log.i(TAG, "SendDataToNetwork: Writing received message to socket");
        new Thread(new Runnable() {
            public void run() {
                try {
                    _nos.write(cmd);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "SendDataToNetwork: Message send failed. Caught an exception");
                }
            }
        }).start();

        return true;
    }

    Log.i(TAG, "SendDataToNetwork: Cannot send message. Socket is closed");
    return false;
}
<uses-permission android:name="android.permission.INTERNET" />
import android.app.Activity;
import android.app.AlertDialog;
import android.app.IntentService;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Main extends Activity {
    final static String TAG = "AndroidCheatSocket";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        TextView textView;

        final String defaultHostname = "192.168.0.";
        textView = new TextView(this);
        textView.setText("hostname / IP:");
        linearLayout.addView(textView);
        final EditText hostnameEditText = new EditText(this);
        hostnameEditText.setText(defaultHostname);
        hostnameEditText.setSingleLine(true);
        linearLayout.addView(hostnameEditText);

        textView = new TextView(this);
        textView.setText("port:");
        linearLayout.addView(textView);
        final EditText portEditText = new EditText(this);
        portEditText.setText("12345");
        portEditText.setSingleLine(true);
        linearLayout.addView(portEditText);

        textView = new TextView(this);
        textView.setText("data to send:");
        linearLayout.addView(textView);
        final EditText dataEditText = new EditText(this);
        dataEditText.setText(String.format("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", defaultHostname));
        linearLayout.addView(dataEditText);

        final TextView replyTextView = new TextView(this);
        final ScrollView replyTextScrollView = new ScrollView(this);
        replyTextScrollView.addView(replyTextView);

        final Button button = new Button(this);
        button.setText("contact server");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button.setEnabled(false);
                new MyAsyncTask(Main.this, replyTextView, button).execute(
                        hostnameEditText.getText().toString(),
                        portEditText.getText().toString(),
                        dataEditText.getText().toString());

            }
        });
        linearLayout.addView(button);

        textView = new TextView(this);
        textView.setText("output:");
        linearLayout.addView(textView);
        linearLayout.addView(replyTextScrollView);

        this.setContentView(linearLayout);
    }

    private class MyAsyncTask extends AsyncTask<String, Void, String> {
        Activity activity;
        Button button;
        TextView textView;
        IOException ioException;
        MyAsyncTask(Activity activity, TextView textView, Button button) {
            super();
            this.activity = activity;
            this.textView = textView;
            this.button = button;
            this.ioException = null;
        }
        @Override
        protected String doInBackground(String... params) {
            StringBuilder sb = new StringBuilder();
            try {
                Socket socket = new Socket(
                        params[0],
                        Integer.parseInt(params[1]));
                OutputStream out = socket.getOutputStream();
                out.write(params[2].getBytes());
                InputStream in = socket.getInputStream();
                byte buf[] = new byte[1024];
                int nbytes;
                while ((nbytes = in.read(buf)) != -1) {
                    sb.append(new String(buf, 0, nbytes));
                }
                socket.close();
            } catch(IOException e) {
                this.ioException = e;
                return "error";
            }
            return sb.toString();
        }
        @Override
        protected void onPostExecute(String result) {
            if (this.ioException != null) {
                new AlertDialog.Builder(this.activity)
                    .setTitle("An error occurrsed")
                    .setMessage(this.ioException.toString())
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
            } else {
                this.textView.setText(result);
            }
            this.button.setEnabled(true);
        }
    }
}