1.IDEA中模块中有一张图片,建立客户端和服务端,客户端建立读写流读取照片的信息,然后通过Socket建立输出流,写出读写流读取的字节。
2.服务端建立ServerSoket指定端口名,让客户端连接,服务端建立一个输出流,服务端调用accept建立输入流,输入流读写客户端发送过来的信息,然后输出流写出输入流读写的信息。
3.确定服务端收到图片,给客户端一个反馈,与以上类似操作。
4.要注意有反馈的情况下客户端输出图片会出现阻塞,需要在客户端读写图片下手动shutdownOutput(),才能结束。
5.最后关闭流操作。
package SocketTest; import org.junit.jupiter.api.Test; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Test2 { @Test public void Client(){ Socket socket = null; OutputStream out = null; BufferedInputStream bs = null; ByteArrayOutputStream bs1 = null; InputStream in = null; try { socket = new Socket(InetAddress.getByName("127.0.0.1"),7788); out = socket.getOutputStream(); bs = new BufferedInputStream(new FileInputStream("th.jpg")); byte[]arr = new byte[1024]; int len; while ((len=bs.read(arr))!=-1) { out.write(arr,0,len); } socket.shutdownOutput(); bs1 = new ByteArrayOutputStream(); in = socket.getInputStream(); byte[]arr1 = new byte[122]; int len1 ; while ((len1 = in.read(arr1))!=-1) { bs1.write(arr1,0,len1); } System.out.println(bs1.toString()); } catch (IOException e) { e.printStackTrace(); } finally { if (bs1!=null) { try { bs1.close(); } catch (IOException e) { e.printStackTrace(); } } if (in!=null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket!=null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if (out!=null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (bs!=null) { try { bs.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void Server(){ ServerSocket ss = null; Socket accept = null; InputStream in = null; OutputStream out= null; BufferedOutputStream bo = null; try { ss = new ServerSocket(7788); accept = ss.accept(); in = accept.getInputStream(); bo = new BufferedOutputStream(new FileOutputStream("th1.jpg")); byte [] arr = new byte[1024]; int len; while ((len = in.read(arr))!=-1) { bo.write(arr,0,len); } out= accept.getOutputStream(); out.write("已经收到图片".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if (out!=null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (ss!=null) { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } if (ss!=null) { try { accept.close(); } catch (IOException e) { e.printStackTrace(); } } if (ss!=null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (ss!=null) { try { bo.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
java TCP简易网络编程
最新推荐文章于 2024-06-04 07:30:00 发布