android socket 客户端实例

   整个流程为:点击连接按钮后,客户端请求与服务器连接,同时开启接受数据的新线程。成功后可在文本框里输入发送的内容,点击发送则发送,同时程序可以不断地接收服务器信息。

下面在讲述几点比较坑的点:
1、切忌,一定要在一个新线程中编写socket,或者添加以下代码

//*******解决主线程访问网络的问题
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork() // or .detectAll() for all detectable problems
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());
//        ************

2、在配置文件中添加以下代码

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

3、使用如下代码传输数据时

BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

每次发送完数据,一定要调用flush()和close()方法。不然会一直接收不到数据

下面附上完整的代码

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;



/**
 * Created by liyongqi on 2016/8/7.
 */
public class Client extends Activity
{
    private EditText mEditText = null;
    private Button connectButton = null;
    private Button sendButton = null;
//    private TextView mTextView = null;
    private Socket clientSocket = null;
    private OutputStream outStream = null;
    private Handler mHandler = null;
    private ReceiveThread mReceiveThread = null;
    private boolean stop = true;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mian);
        //*******解决主线程访问网络的问题
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork() // or .detectAll() for all detectable problems
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());
//        ************
        mEditText = (EditText) this.findViewById(R.id.edittext);
//        mTextView = (TextView) this.findViewById(R.id.retextview);
        connectButton = (Button) this.findViewById(R.id.connectbutton);
        sendButton = (Button) this.findViewById(R.id.sendbutton);
        sendButton.setEnabled(false);
        // 连接按钮监听
        connectButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                try
                {
                    // 实例化对象并连接到服务器
                    clientSocket = new Socket("192.168.1.157",8889);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.d("Client","连接成功");
                // 连接按钮使能
                connectButton.setEnabled(false);
                // 发送按钮使能
                sendButton.setEnabled(true);
                mReceiveThread = new ReceiveThread(clientSocket);
                stop = false;
                // 开启线程
                mReceiveThread.start();
            }
        });
        //发送数据按钮监听
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BufferedWriter bufferedWriter=null;
                try {
                    bufferedWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
                } catch (IOException e) {
                    Log.d("Client","BufferedWriter出错");
                    e.printStackTrace();
                }
                // 获得EditTex的内容
                String text = mEditText.getText().toString();
                Log.d("Client","即将发送的信息为:"+text);
                try {
                    // 发送数据
                   bufferedWriter.write(text);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                } catch (IOException e) {
                    Log.d("Client","发送数据出错");
                    e.printStackTrace();
                }
                Log.d("Client","成功发送数据");
                // 清空内容
                mEditText.setText("");

            }
        });
    }

    private class ReceiveThread extends Thread
    {

        private  BufferedReader in = null;
        private String str = null;
        ReceiveThread(Socket s) {
            try {
                // 获得输入流
                in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
            while (!stop) {
                // 读取输入的数据(阻塞读)
                try {
                    String s=in.readLine();
                    Log.d("Client",s);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mReceiveThread != null) {
            stop = true;
            mReceiveThread.interrupt();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值