客户端:
//客户端上传文件
public class SocketTest {
public static void main(String[] args) throws IOException {
//1.创建客户端对象
Socket socket = new Socket(“192.168.3.54”,32);
//2.创建输入流文件
FileInputStream f1 = new FileInputStream(new File(“F:\images\love.jpg”));
//3.创建输出流
OutputStream out = socket.getOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len=f1.read(bytes))!=-1){
out.write(bytes);
}
//4.创建输入流:接收服务端发来的信息
InputStream in = socket.getInputStream();
byte[] bytes1 = new byte[1024];
int read = in.read(bytes1);
System.out.println(new String(bytes,0,read));
//释放资源
in.close();
out.close();
f1.close();
socket.close();
}
}
服务端:
//服务器接收文件
public class ServerSocketTest {
public static void main(String[] args) throws IOException {
//1.创建服务器对象
ServerSocket server = new ServerSocket(32);
//2.获取客户端对象
Socket accept = server.accept();
//4.将文件读取到本地磁盘:读取客户端发来的文件(图片)
InputStream in = accept.getInputStream();
//3.创建字节输出流
FileOutputStream f1= new FileOutputStream(newFile(“D:\Develop\Workspack\javase\Demo1\day_18\src\UPText\2.jpg”));
//小重点
byte[] bytes = new byte[1024];
int len = 0;
while ((len=in.read(bytes))!=-1){
f1.write(bytes,0,len);
}
//5.创建输出流
OutputStream out = accept.getOutputStream();
out.write(“文件已经收到,放心!”.getBytes());
//6.释放资源
out.close();
in.close();
f1.close();
accept.close();
server.close();
}
总结:
1.使用字节流来读取文件(图片)
2.创建输出流将读取到的文件(图片通过Socket通道发送给服务端)
3.服务端:创建输入流(读取客户端上传的文件[图片]),然后再创建输出流将读取到的文件保存到本体文件夹中.
4.创建输出流: OutputStream out = accept.getOutputStream(),将已经读成功文件,以信息发送给客户端
5.客户端创建输入流,读取服务端发来的信息
InputStream in = socket.getInputStream();