所有东西 为自己理解,有的地方会不准,如果有高手可以指出,非常感谢。
这里对使用socket
//流读取工具类
public class StreamUtil {
//正常读取本地文件的时可以用,但用于网络传输读取数据时会有问题
//一旦 网络中另一方的数据没有返回到 这边 则会出现阻塞状态
public static byte[] readStream(InputStream is ) throws IOException{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
// is.read( buffer,0,lenth )
while( is.read( buffer ) !=-1 ){
outStream.write(buffer );
}
is.close();
outStream.close();
return outStream.toByteArray();
}
//调用 availble 可用于网络上读取数据
public static byte[] readStreamAvailble(InputStream is ) throws IOException{
int len =0;
while(len==0){
//如果服务端 没有数据返回则 不断的取数据 ,直到取到数据位置 ,一旦出现阻塞则数据则会不准确
len = is.available();
}
byte[] bs = new byte[len];
is.read( bs );
return bs;
}
//测试
public static void main(String[] args) throws IOException {
File file = new File("e:/1113.txt");
InputStream is = new FileInputStream(file);;
byte[] str = readStream( is);
System.out.println( new String(str) );
}
}
-------socket 服务端 使用 网络读取数据
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8001);
while(true ){
Socket socket = server.accept();
//对于每个客户端的请求 每个请求创建一个线程来回应
new Thread(new ServerImpl( socket )).start();
}
}
}
==========客户端
public class Client {
public static void main(String[] args) { client2(); } /** * 测试 过期时间 设置 * @Title: client2 * @Description: * @param * @return void * @throws */ public static void client2(){ Socket socket = null; try { socket = new Socket("127.0.0.1", 8001); socket.setKeepAlive(true); while(true && null != socket){
//服务器阻塞 Thread.sleep(10 * 1000); } } catch ( Exception e) { e.printStackTrace(); } } /** * 测试输入流 * @Title: client1 * @Description: * @param * @return void * @throws */ public static void client1(){ Socket socket = null; OutputStream os = null; InputStream is = null ; try { socket = new Socket("127.0.0.1", 8001); socket.setKeepAlive(true); socket.setSoTimeout( 30*1000 ); os = socket.getOutputStream(); os.write( "服务器你好:".getBytes()); is = socket.getInputStream(); byte[] bs = StreamUtil.readStreamAvailble(is); System.out.println( "服务器的消息:"+ new String(bs )); is.close(); os.close(); socket.close(); } catch ( Exception e) { e.printStackTrace(); }finally{ try { if(is!=null ){ is.close(); } if(os!=null){ os.close(); } if(socket!=null){ socket.close(); } } catch (IOException e) { e.printStackTrace(); } } }
}
参考:
http://cuisuqiang.iteye.com/blog/1434416