网络编程-TCP连接-length

在使用readLine方式时,常常会遇到因为没有结束标记,而导致阻塞现象。

如果不想使用结束标记,这里可以使用一个固定长度的byte[],来获取流。

server

package com.net.tcp.length;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServerL {

    public static void main(String[] args) {
        
            ServerSocket ss;
            try {
                ss = new ServerSocket(30000);
                Socket s= ss.accept();
                byte[] rin = new byte[8];
                s.getInputStream().read(rin);
                System.out.println(new String(rin,0,8));
            
                
                PrintStream ps = new PrintStream(s.getOutputStream());
                ps.println("收到消息aa");
                ps.flush();
                ps.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                }                

}

Client

package com.net.tcp.length;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class MyClientL {

    public static void main(String[] args) {
        Socket s = new Socket();
        try {
            s.connect(new InetSocketAddress("127.0.0.1", 30000), 10000);
            PrintStream ps = new PrintStream(s.getOutputStream());
            ps.println("发送消息aa");
            ps.flush();
            
            byte[] rin = new byte[8];
            s.getInputStream().read(rin);
            System.out.println(new String(rin,0,8));
            
            ps.close();
            s.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

 

posted @ 2016-05-23 09:54  月色深潭  阅读(378)  评论(0编辑  收藏  举报