本次传输是基于TCP协议进行传输,其实传输图片的写法和传输文件的写法是差不多的
客户端:
package com.day1;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ClientPicture {
public static void main(String[] args) throws Exception {
//1.连接诶服务器
Socket s = new Socket("127.0.0.1",9999);
System.out.println("已连接到服务器9999端口,准备传送图片...");
//获取图片字节流
FileInputStream fis = new FileInputStream("src\\img\\1_2.jpg");
//获取输出流
//OutputStream out = s.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());
byte[] buf = new byte[1024];
int len = 0;
//2.往输出流里面投放数据
while ((len = fis.read(buf)) != -1)
{
bos.write(buf,0,len);
}
//通知服务端,数据发送完毕
s.shutdownOutput();
//3.获取输出流,接受服务器传送过来的消息“上传成功”
//InputStream in = s.getInputStream();
BufferedInputStream bis=new BufferedInputStream(s.getInputStream());
byte[] bufIn = new byte[1024];
int num = bis.read(bufIn);
System.out.println(new String(bufIn,0,num));
//关闭资源
fis.close();
bos.close();
bis.close();
s.close();
}
}
服务器端
package com.day1;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
//使用TCp进行图片传输
//服务器端
public class ServerPicture {
public static void main(String[] args) throws Exception {
ServerSocket ss=new ServerSocket(9999);
System.out.println("服务器端以及启动正在接受数据");
Socket s=ss.accept();
System.out.println("检测到客户端");
InputStream in=s.getInputStream();
FileOutputStream fos=new FileOutputStream("src\\com\\day1\\2.jpg");
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1) {
fos.write(buf,0,len);
}
//收到图片,给客户端回送信息
OutputStream out=s.getOutputStream();
out.write("上传成功".getBytes());
//关闭资源
fos.close();
in.close();
out.close();
s.close();
ss.close();
}
}