一、客户端代码
public class UploadPicClient {
public static void main(String[] args) throws IOException {
//新建一个客户端socket,确定服务端的ip和端口
Socket s = new Socket("192.168.1.100",10007);
//源:创建读取指定图片的读取流
FileInputStream fis = new FileInputStream("F:\\Desert.jpg");
//目的:获取socket的输出流
OutputStream out = s.getOutputStream();
//频繁读写
int len = 0;
byte[] buf = new byte[1024];
while((len=fis.read(buf))!=-1){
out.write(buf,0,len);
}
//告诉服务端图片发送完毕,不要等着读了
s.shutdownOutput();
//读取服务器反馈的成功消息
InputStream in = s.getInputStream();
byte[] bufIn = new byte[1024];
int lenIn = in.read(bufIn);
System.out.println(new String(bufIn,0,lenIn));
//关闭
fis.close();
s.close();
}
}
二、服务端代码
public class UploadPicServer {
public static void main(String[] args) throws IOException {
System.out.println("上传图片服务端运行...");
//创建server socket
ServerSocket ss = new ServerSocket(10007);
while (true){
//获取客户端
Socket s = ss.accept();
//实现多个客户端并发上传,服务器端必须启动做个线程来完成
//这样主线程就可以只负责接收客户端连接,上传图片的执行交给下面创建的新线程处理
new Thread(new UploadPic(s)).start();
}
}
}
三、服务端写的线程任务类UploadPic代码:
public class UploadPic implements Runnable{
private Socket s;
public UploadPic(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"...connnected");
//读取图片数据
InputStream in = s.getInputStream();
//写图片数据到文件,
File dir = new File("f:\\uploadpic");
if(!dir.exists()){
dir.mkdir();
}
//为了避免覆盖,通过给重名的文件进行编号
int count=1;
File picFile = new File(dir,ip+"("+count+").jpg");
while (picFile.exists()){
count++;
picFile = new File(dir,ip+"("+count+").jpg");
}
FileOutputStream fos = new FileOutputStream(picFile);
int len = 0;
byte[] buf = new byte[1024];
while ((len=in.read(buf))!=-1){
fos.write(buf,0,len);
}
//给客户端一个回馈信息
OutputStream out = s.getOutputStream();
out.write("上传成功".getBytes());
//关闭资源
fos.close();
s.close();
} catch (IOException e) {
}
}
}