赞
踩
@Test public void testServer1() throws IOException { ServerSocket serverSocket = new ServerSocket(8899); Socket socket = serverSocket.accept(); //选择流,字符输出字符输入,字节输出字节输入要对应,不能一个字符,一个字节,否则数组长度会改变 //好像不能随便使用转换流,会报错 InputStream socketInputStream = socket.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream("Test929.txt"); byte[] bytes = new byte[1024]; int len; //.read()方法有个阻塞的功能,如果对方不说发送已经完成,我便一直等着你继续发送直到你说发送完成 //socket.shutdownOutput(); while ((len = socketInputStream.read(bytes)) != -1) { fileOutputStream.write(bytes, 0, len); } OutputStream outputStream = socket.getOutputStream(); outputStream.write("收到".getBytes()); socketInputStream.close(); fileOutputStream.close(); outputStream.close(); }
@Test public void testClient1() throws IOException { Socket socket = new Socket("10.212.10.194", 8899); //选择流,字符输出字符输入,字节输出字节输入要对应,不能一个字符,一个字节,否则数组长度会改变 //好像不能随便使用转换流,会报错 OutputStream socketOutputStream = socket.getOutputStream(); //文件格式不对会乱码也不要自己去使用转换流,因为本来就是文件从客户端发到服务端,不需要你去转码,什么是就是什么; FileInputStream fileInputStream = new FileInputStream("Test921.txt"); byte[] bytes = new byte[1024]; int len; while ((len = fileInputStream.read(bytes)) != -1) { socketOutputStream.write(bytes, 0, len); } //输出完成,之后不再输出,给对方信息说我不在发送输出了,且关闭Socket socket.shutdownOutput(); InputStream inputStream = socket.getInputStream(); //byte[] bytes = new byte[1024]; while ((len = inputStream.read(bytes)) != -1) { System.out.println(new String(bytes, 0, len)); } fileInputStream.close(); socketOutputStream.close(); inputStream.close(); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。