黑马程序员技术交流社区
标题:
练习多人上传图片
[打印本页]
作者:
奋发吧小白
时间:
2014-11-6 16:44
标题:
练习多人上传图片
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
//创建ServerSocket服务
ServerSocket ss = new ServerSocket(9003);
while(true)
{
//获取客户端对象
Socket s = ss.accept();
new Thread(new TreadUP(s)).start();
System.out.println("sdas");
}
}
}
复制代码
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args)throws Exception {
//只能传入一个文件
if(args.length!=1)
{
System.out.println("请选择一个.jp文件");
return;
}
//把传入的文件封装成对象
File file = new File(args[0]);
//判断文件是否存在,并且文件后缀为.jpg
if(!(file.exists()&&file.isFile()))
{
System.out.println("文件不存在或者不是文件");
return;
}
//判断文件格式
if(!(file.getName().endsWith(".jpg")))
{
System.out.println("文件格式不正确,应该选择文件格式为.jpg文件");
return;
}
//判断文件大小
if(file.length()>1024*104*5)
{
System.out.println("文件过大请重新选择,文件大小应该小于5M");
return ;
}
//创建Socket服务
Socket s = new Socket("192.168.0.107",9003);
//获取Socket输出流
BufferedOutputStream bufOut = new BufferedOutputStream(s.getOutputStream());
//获取Socket读取流
BufferedReader bufIn = new BufferedReader(
new InputStreamReader(s.getInputStream()));
//读取硬盘文件流
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
//将读取到的硬盘数据打印到服务端
byte [] buf = new byte [1024];
int len = 0;
while((len = bis.read(buf))!=-1)
{
bufOut.write(buf, 0, len);
bufOut.flush();
}
s.shutdownOutput();
//接收服务端返回的数据
String str = bufIn.readLine();
System.out.println("Server:"+str);
s.close();
bis.close();
}
}
复制代码
import java.io.*;
import java.net.*;
public class TreadUP implements Runnable{
private Socket s;
public TreadUP(Socket s)
{
this.s = s;
}
public void run()
{
int count = 1;
//获取客户端IP地址
String IP = s.getInetAddress().getHostAddress();
try {
//把上传的文件按照IP地址命名
File file = new File("D:\\",IP+"("+count+")"+".jpg");
//判断文件是否存在,若是存在在后面(1)的形式重新命名
while(file.exists())
{
file = new File("D:\\",IP+"("+(count++)+")"+".jpg");
}
//获取客户端读取流
BufferedInputStream bufIn = new BufferedInputStream(s.getInputStream());
//获取客户端输出流
BufferedWriter bufOut = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
//把Socket流中的数据写入到文件
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
//循环读取客户端发送的数据
byte [] buf = new byte[1024];
int len = 0;
while((len = bufIn.read(buf))!=-1)
{
bos.write(buf, 0, len);
bos.flush();
}
s.shutdownInput();
bufOut.write("上传成功!");
bufOut.newLine();
bufOut.flush();
s.close();
bos.close();
} catch (Exception e) {
throw new RuntimeException(IP+"上传失败");
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2