|
30鱼币
本帖最后由 Aojacy 于 2019-9-23 22:58 编辑
- package netStream;
- import org.junit.Test;
- import java.io.*;
- import java.net.*;
- public class SocketTest2 {
- @Test
- public void clientTest() {
- Socket socket = null;
- OutputStream os = null;
- try {
- socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
- os = socket.getOutputStream();
- FileInputStream fis = new FileInputStream(new File("hello1.jpg"));
- byte[] buff = new byte[1024];
- int len;
- while ((len = fis.read(buff))!=-1){
- os.write(buff,0,len);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if(os!=null){
- try {
- os.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(socket!=null){
- try {
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- @Test
- public void serveTest() throws IOException {
- ServerSocket serverSocket = null;
- Socket acceptSocket = null;
- InputStream is = null;
- FileOutputStream fos = null;
- try {
- serverSocket = new ServerSocket(9090);
- acceptSocket = serverSocket.accept();
- is = acceptSocket.getInputStream();
- fos = new FileOutputStream(new File("hello2.jpg"));
- byte[] buff = new byte[1024];
- int len;
- while ((len = is.read(buff))!=-1){
- fos.write(buff,0,len);
- }
- System.out.println("复制成功");
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if(fos!=null){
- fos.close();
- }
- if(is!=null){
- is.close();
- }
- if(acceptSocket!=null){
- acceptSocket.close();
- }
- if(serverSocket!=null){
- serverSocket.close();
- }
- }
- }
- }
复制代码
按理说第57行不会执行到,上面循环会进入阻塞,为什么实际没有阻塞? |
|