socket模拟通信
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class client { public static void main(String[] args) throws UnknownHostException, IOException { Socket socket= new Socket( "192.168.1.106" , 9991 ); InputStream in=socket.getInputStream(); byte []bytes= new byte [ 100 ]; OutputStream o= new FileOutputStream( "/root/桌面/12.txt" ); int len= 3 ; while ((in.read(bytes))!=- 1 ) { o.write(bytes, 0 , len); } o.close(); in.close(); socket.close(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class socketserver { public static void main(String[] args) throws IOException { ServerSocket socket= new ServerSocket( 9991 ); //默认本机ip Socket s=socket.accept(); System.out.println( "ok" ); OutputStream o=s.getOutputStream(); String dd= "hello" ; o.write(dd.getBytes()); File f= new File( "D:\\ip01.png" ); InputStream in= new FileInputStream(f); byte []bytes= new byte [ 100 ]; int len= 9 ; while ((len=in.read(bytes))!=- 1 ) { o.write(bytes, 0 ,len); } // System.out.println("sesrvershoudao:"+new String(bytes)); o.close(); in.close(); socket.close(); s.close(); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步