TCP socket 长连接

来源:互联网 发布:五格剖象法 软件 编辑:程序博客网 时间:2024/05/01 03:22

1. 需要开启两个线程,一个线程一直监听连接,一个线程数据传输

2. 连接线程

if (mSocket != null) {
       mSocket.close();
       mSocket = null;
   }
 mSocket = new Socket();
   mSocket.setTcpNoDelay(true);
   mSocket.setKeepAlive(true);
   SocketAddress remoteAddr = new InetSocketAddress(   mIp, mPort);
    mSocket.connect(remoteAddr, 5000);

//数据监听线程
     connected();
   }

2. 数据传输线程

mInStream = mSocket.getInputStream();
 mOutStream = mSocket.getOutputStream();

 int readLen = 0; 

   byte[] buf = null;
   int totalLen = 0;    

while (mRunFlag) {

      mSocket.sendUrgentData(0xFF);
     totalLen = mInStream.available();
      if (totalLen <= 0) 
      Thread.sleep(500);
     continue;
    }

    buf = new byte[totalLen];
    while (readLen < totalLen) {
      readLen += mInStream.read(buf, readLen, totalLen- readLen);
    }

    buf = null;
    readLen = 0;

原创粉丝点击