TCP 简单

1、

Client 连接 Server :

 1         InetSocketAddress endpoint = new InetSocketAddress(FstrDestIP , FstrDestPort); 
 2         
 3         Socket Fsock = new Socket();//(FstrDestIP, 445);
 4         Fsock.connect(endpoint, 1000);
 5         Fsock.setTcpNoDelay(true); //关闭Nagle算法.立即发包
 6         */
 7         //设置发送逗留时间2秒 //中断后未传输数据可传输的时间(秒),defalut false
 8         //socket.setSoLinger(true, 2); 
 9         //设置InputStream上调用 read()阻塞超时时间2秒 
10         //socket.setSoTimeout(2000); 

 

2、

接收消息 :

 1     @Override
 2     public void run()
 3     {
 4         //super.run();
 5         
 6         System.out.println("Thread in .");
 7         try
 8         {
 9             InputStream is = Fsock.getInputStream();
10             while (true)
11             {
12                 byte[] bytesRecv = new byte[1024];
13                 int iRecvLen = is.read(bytesRecv);
14                 if ((iRecvLen == 0) || (-1 == iRecvLen))
15                 {
16                     System.out.println("Thread out (1)");
17                     break; // 退出循环
18                 }
19                 
20                 for (int i=0; i<iRecvLen; i++)
21                 {
22                     System.out.println(bytesRecv[i]+" ");
23                 }
24             } // while
25             is.close();
26             Fsock.close();
27             System.out.println("Thread out (2)");
28         }
29         catch (IOException e)
30         {
31             e.printStackTrace();
32         }
33     }

 

3、

发送信息:

    public void SendBytes(byte[] _bytesSend) throws Exception
    {
        OutputStream os = Fsock.getOutputStream(); 
        os.write(_bytesSend);
    }

 

 

 

 

 

 

 

 

S

posted @ 2015-11-07 17:09  codeskill_android  阅读(120)  评论(0编辑  收藏  举报