public class FileServer
{
private ExecutorService executorService;
private int port;
private boolean quit = false;
private ServerSocket server;
private Map<Long, FileLog> datas = new HashMap<Long, FileLog>();
public FileServer(int port)
{
this.port = port;
executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 50);
}
public void quit()
{
this.quit = true;
try
{
server.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void start() throws Exception
{
server = new ServerSocket(port);
while(!quit)
{
try
{
Socket socket = server.accept();
executorService.execute(new SocketTask(socket));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private final class SocketTask implements Runnable
{
private Socket socket = null;
public SocketTask(Socket socket)
{
this.socket = socket;
}
@Override
public void run()
{
try
{
System.out.println("accepted connection "+ socket.getInetAddress()+ ":"+ socket.getPort());
PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
String head = StreamTool.readLine(inStream);
System.out.println(head);
if(head!=null)
{
String[] items = head.split(";");
String filelength = items[0].substring(items[0].indexOf("=")+1);
String filename = items[1].substring(items[1].indexOf("=")+1);
String sourceid = items[2].substring(items[2].indexOf("=")+1);
long id = System.currentTimeMillis();
FileLog log = null;
if(sourceid!=null && !"".equals(sourceid))
{
id = Long.valueOf(sourceid);
log = find(id);
}
File file = null;
int position = 0;
if(log==null)
{
String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm").format(new Date());
File dir = new File("file/"+ path);
if(!dir.exists()) dir.mkdirs();
file = new File(dir, filename);
if(file.exists())
{
filename = filename.substring(0, filename.indexOf(".")-1)+ dir.listFiles().length+ filename.substring(filename.indexOf("."));
file = new File(dir, filename);
}
save(id, file);
}
else
{
file = new File(log.getPath());
if(file.exists())
{
File logFile = new File(file.getParentFile(), file.getName()+".log");
if(logFile.exists())
{
Properties properties = new Properties();
properties.load(new FileInputStream(logFile));
position = Integer.valueOf(properties.getProperty("length"));
}
}
}
OutputStream outStream = socket.getOutputStream();
String response = "sourceid="+ id+ ";position="+ position+ "/r/n";
outStream.write(response.getBytes());
RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd");
if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));
fileOutStream.seek(position);
byte[] buffer = new byte[1024];
int len = -1;
int length = position;
while( (len=inStream.read(buffer)) != -1)
{
fileOutStream.write(buffer, 0, len);
length += len;
Properties properties = new Properties();
properties.put("length", String.valueOf(length));
FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+".log"));
properties.store(logFile, null);
logFile.close();
}
if(length==fileOutStream.length()) delete(id);
fileOutStream.close();
inStream.close();
outStream.close();
file = null;
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(socket!=null && !socket.isClosed()) socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public FileLog find(Long sourceid)
{
return datas.get(sourceid);
}
public void save(Long id, File saveFile)
{
datas.put(id, new FileLog(id, saveFile.getAbsolutePath()));
}
public void delete(long sourceid)
{
if(datas.containsKey(sourceid)) datas.remove(sourceid);
}
private class FileLog{
private Long id;
private String path;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public FileLog(Long id, String path) {
this.id = id;
this.path = path;
}
}
}
(1)Android客户端代码:
public class UploadLogService
{
private DBOpenHelper dbOpenHelper;
public UploadLogService(Context context)
{
this.dbOpenHelper = new DBOpenHelper(context);
}
public void save(String sourceid, File uploadFile)
{
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("insert into uploadlog(uploadfilepath, sourceid) values(?,?)",
new Object[]{uploadFile.getAbsolutePath(),sourceid});
}
public void delete(File uploadFile)
{
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("delete from uploadlog where uploadfilepath=?", new Object[]{uploadFile.getAbsolutePath()});
}
public String getBindId(File uploadFile)
{
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select sourceid from uploadlog where uploadfilepath=?",
new String[]{uploadFile.getAbsolutePath()});
if(cursor.moveToFirst())
{
return cursor.getString(0);
}
return null;
}
}
public class DBOpenHelper extends SQLiteOpenHelper
{
public DBOpenHelper(Context context)
{
super(context, "upload.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE uploadlog (_id integer primary key autoincrement, uploadfilepath varchar(100), sourceid varchar(10))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS uploadlog");
onCreate(db);
}
}
public class UploadActivity extends Activity
{
private EditText filenameText;
private TextView resulView;
private ProgressBar uploadbar;
private UploadLogService logService;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
logService = new UploadLogService(this);
filenameText = (EditText)this.findViewById(R.id.filename);
uploadbar = (ProgressBar) this.findViewById(R.id.uploadbar);
resulView = (TextView)this.findViewById(R.id.result);
Button button =(Button)this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String filename = filenameText.getText().toString();
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
File uploadFile = new File(Environment.getExternalStorageDirectory(), filename);
if(uploadFile.exists())
{
uploadFile(uploadFile);
}
else
{
Toast.makeText(UploadActivity.this, R.string.filenotexsit, 1).show();
}
}
else
{
Toast.makeText(UploadActivity.this, R.string.sdcarderror, 1).show();
}
}
});
}
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
int length = msg.getData().getInt("size");
uploadbar.setProgress(length);
float num = (float)uploadbar.getProgress()/(float)uploadbar.getMax();
int result = (int)(num * 100);
resulView.setText(result+ "%");
if(uploadbar.getProgress()==uploadbar.getMax())
{
Toast.makeText(UploadActivity.this, R.string.success, 1).show();
}
}
};
private void uploadFile(final File uploadFile)
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
uploadbar.setMax((int)uploadFile.length());
String souceid = logService.getBindId(uploadFile);
String head = "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+
(souceid==null? "" : souceid)+"/r/n";
Socket socket = new Socket("192.168.1.100", 7878);
OutputStream outStream = socket.getOutputStream();
outStream.write(head.getBytes());
PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
String response = StreamTool.readLine(inStream);
String[] items = response.split(";");
String responseid = items[0].substring(items[0].indexOf("=")+1);
String position = items[1].substring(items[1].indexOf("=")+1);
if(souceid==null)
{
logService.save(responseid, uploadFile);
}
RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");
fileOutStream.seek(Integer.valueOf(position));
byte[] buffer = new byte[1024];
int len = -1;
int length = Integer.valueOf(position);
while( (len = fileOutStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
length += len;
Message msg = new Message();
msg.getData().putInt("size", length);
handler.sendMessage(msg);
}
fileOutStream.close();
outStream.close();
inStream.close();
socket.close();
if(length==uploadFile.length())
logService.delete(uploadFile);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
}
public class StreamTool
{
public static void save(File file, byte[] data) throws Exception
{
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
}
public static String readLine(PushbackInputStream in) throws IOException
{
char buf[] = new char[128];
int room = buf.length;
int offset = 0;
int c;
loop: while (true) {
switch (c = in.read())
{
case -1:
case '/n':
break loop;
case '/r':
int c2 = in.read();
if ((c2 != '/n') && (c2 != -1)) in.unread(c2);
break loop;
default:
if (--room < 0) {
char[] lineBuffer = buf;
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
}
buf[offset++] = (char) c;
break;
}
}
if ((c == -1) && (offset == 0)) return null;
return String.copyValueOf(buf, 0, offset);
}
public static byte[] readStream(InputStream inStream) throws Exception
{
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len=inStream.read(buffer)) != -1){
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
}
public class SocketClient
{
public static void main(String[] args)
{
try
{
Socket socket = new Socket("127.0.0.1", 7878);
OutputStream outStream = socket.getOutputStream();
String filename = "QQWubiSetup.exe";
File file = new File(filename);
String head = "Content-Length="+ file.length() + ";filename="+ filename + ";sourceid=1278916111468/r/n";
outStream.write(head.getBytes());
PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
String response = StreamTool.readLine(inStream);
System.out.println(response);
String[] items = response.split(";");
String position = items[1].substring(items[1].indexOf("=")+1);
RandomAccessFile fileOutStream = new RandomAccessFile(file, "r");
fileOutStream.seek(Integer.valueOf(position));
byte[] buffer = new byte[1024];
int len = -1;
int i = 0;
while( (len = fileOutStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
i++;
}
fileOutStream.close();
outStream.close();
inStream.close();
socket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static byte[] readStream(InputStream inStream) throws Exception
{
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len=inStream.read(buffer)) != -1)
{
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
}
public class ServerWindow extends Frame
{
private FileServer s = new FileServer(7878);
private Label label;
public ServerWindow(String title)
{
super(title);
label = new Label();
add(label, BorderLayout.PAGE_START);
label.setText("服务器已经启动");
this.addWindowListener(new WindowListener()
{
@Override
public void windowOpened(WindowEvent e)
{
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
s.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
s.quit();
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
});
}
public static void main(String[] args)
{
ServerWindow window = new ServerWindow("文件上传服务端");
window.setSize(300, 300);
window.setVisible(true);
}
}
public class StreamTool
{
public static void save(File file, byte[] data) throws Exception
{
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
}
public static String readLine(PushbackInputStream in) throws IOException
{
char buf[] = new char[128];
int room = buf.length;
int offset = 0;
int c;
loop: while (true) {
switch (c = in.read()) {
case -1:
case '/n':
break loop;
case '/r':
int c2 = in.read();
if ((c2 != '/n') && (c2 != -1)) in.unread(c2);
break loop;
default:
if (--room < 0) {
char[] lineBuffer = buf;
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
}
buf[offset++] = (char) c;
break;
}
}
if ((c == -1) && (offset == 0)) return null;
return String.copyValueOf(buf, 0, offset);
}
public static byte[] readStream(InputStream inStream) throws Exception
{
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len=inStream.read(buffer)) != -1)
{
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
}