JAVA信息传送代码之下载图片
package xin.week1.day3;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/*首先开启客户端服务
* 客户端下载服务端侧的图片*/
public class tcpxiazai {
@Test
public void server() {
ServerSocket ss = null;
Socket socket = null;
FileInputStream fis = null;
OutputStream os = null;
try {
ss = new ServerSocket(9090); //定义端口
socket = ss.accept();
fis = new FileInputStream(new File("Java.jpg")); //客户端图片
os = socket.getOutputStream();
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
os.write(b, 0, len);
}
socket.shutdownOutput();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}}
//客户端
@Test
public void client() {
Socket socket1 = null;
FileOutputStream fos = null;
InputStream is = null;
try {
//匹配服务端IP+端口
socket1 = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
//图片下载位置
fos = new FileOutputStream(new File("E:\\lj\\Java.jpg"));
is = socket1.getInputStream();
byte[] b = new byte[1024];
int len;
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
}
System.out.println("下载成功");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
socket1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
在这里欢迎大家的点赞、关注、评论,以此来促进大家互相学习交流,同时可以让新加入的小伙伴更快的了解新知识!!!
文章内容如有侵权,请联系作者进行删除
≧◠◡◠≦ 1分2分都是爱,感谢已经打赏的老板,和正在打赏的老板们 ≧◠◡◠≦