模拟客户端和服务器的文件传输
使用两个类:
一、ServerSocket
构造方法:ServerSocket(int port)
方法:accept() 返回Socket对象
二、Socket
构造方法:Socket(String ip, int port) :连接指定ip和端口号
方法: getOutputStream() 返回 OutputStream 对象,用于给另一端传流
getInputStream() 返回InputStream 对象,得到另一端传来的流
close() 关闭创建的对象
shutdownOutput() 给传出的流加上结束符号,便于另一端读取
服务器端:
public class dd {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(55565);
Socket socket=serverSocket.accept();
InputStream is=socket.getInputStream();
FileOutputStream fos=new FileOutputStream("C:\\Users\\asus\\Pictures\\Screenshots\\余霜.png");
byte[] bytes=new byte[1024];
int i=0;
while ((i=is.read(bytes))!=-1){
fos.write(bytes);
}
System.out.println("这里成功");
OutputStream os=socket.getOutputStream();
os.write("上传成功".getBytes());
System.out.println(".............");
os.close();
fos.close();
socket.close();
serverSocket.close();
}
}
客户端:
public class aa {
public static void main(String[] args) throws IOException {
Socket socket=new Socket("127.0.0.1",55565);
FileInputStream fi=new FileInputStream("C:\\Users\\asus\\Pictures\\Screenshots\\屏幕截图(1).png");
OutputStream os=socket.getOutputStream();
byte[] bytes=new byte[1024];
while (fi.read(bytes)!=-1){
os.write(bytes);
}
socket.shutdownOutput(); //暂定
System.out.println("这里成功");
InputStream is=socket.getInputStream();
byte[] bytes1=new byte[1024];
int len=is.read(bytes1);
System.out.println(new String(bytes1,0,len));
System.out.println("................");
is.close();
os.close();
fi.close();
socket.close();
}
}