zoukankan      html  css  js  c++  java
  • 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 += "
    ";
                               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());
    }

  • 相关阅读:
    解决Chrome 70及以上版本的证书问题:Failed to load resource: net::ERR_CERT_SYMANTEC_LEGACY
    VUE使用axios数据请求时报错 TypeError: Cannot set property 'xxxx' of undefined 的解决办法
    生辰八字推算
    OneNote巧妙设置标题
    Kibana安装与介绍
    Logstash入门简介
    Metricbeat入门简介
    FileBeats入门简介
    ElasticSearch集群部署
    ElasticSearch安装与介绍
  • 原文地址:https://www.cnblogs.com/huangzhen22/p/4815895.html
Copyright © 2011-2022 走看看