Android之socket客户端

接收数据不要用readline(),用read()

Socket mSocket = new Socket("192.168.1.100", 8888);

DataInputStream dinput = new DataInputStream(mSocket.getInputStream())

读取服务端发过来的数据:

int length = dinput.read(bbuf);
String mStrMSG = new String(bbuf, 0, length, "gb2312");

package com.example.tcp_client;
import java.io.DataInputStream;
import java.io.PrintWriter;
import java.net.Socket;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;

@SuppressLint("NewApi") public class TCPClient implements Runnable{
    private static final String SERVERIP = "192.168.1.100";
    private static final int SERVERPORT = 8888;
    private Thread mThread = null;
    private static Socket mSocket = null;
    private DataInputStream dinput;
    private static PrintWriter mPrintWriter = null;
    private static  String mStrMSG = "";
    private static String TAG = "TCPClient";
    //接收线程发送过来信息,并用TextView显示
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e("服务器说:", mStrMSG);
            MainActivity.AppendText("服务器说:"+mStrMSG);    
        }
    }; 
   public  void StartTCPClient(){
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
        try
        {
            // ①Socket实例化,连接服务器
            mSocket = new Socket(SERVERIP, SERVERPORT);
            // ②获取Socket输入输出流进行读写操作
            dinput=new DataInputStream(mSocket.getInputStream());
            mPrintWriter = new PrintWriter(mSocket.getOutputStream(), true);
            new Thread(TCPClient.this).start();
        } catch (Exception e)
        {
            Log.e(TAG, e.toString());
        }
   }
   
   public static void SendToServer(String sendmsg){
       mPrintWriter.print(sendmsg);
       mPrintWriter.flush();
   }
   
   /**
    * 读取服务器发来的信息,并通过Handler发给UI线程
    */
   public void run() {
       try {
           byte[] bbuf = new byte[10000];
           while (true) {
               
               if (!mSocket.isClosed()) {
                   if (mSocket.isConnected()) {
                       if (!mSocket.isInputShutdown()) {
                           int length = dinput.read(bbuf);
                              mStrMSG = new String(bbuf, 0, length, "gb2312");
                              mStrMSG += "\n";
                           mHandler.sendMessage(mHandler.obtainMessage());
                       }
                   }
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
}
TCP服务端

使用实例化即可

try
{
tcpclient =new TCPClient();
tcpclient.StartTCPClient();
} catch (Exception e)
{
// TODO: handle exception
Log.e("MainActivity", e.toString());
}

posted @ 2015-09-17 11:46  黄忠  阅读(297)  评论(0编辑  收藏  举报