socket模拟通信
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(); } }
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(); } }