import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class DataServer2 {
public static final int SERVICE_PORT=1500;
public static final int DATA_SIZE=1024;
public static final String FILE_PATH = "C:\\MP4\\";
public static String FILE_NAME;
public static void main(String[] args) {
String filePath = FILE_PATH;
try{
ServerSocket server = new ServerSocket(SERVICE_PORT);
System.out.println("Service started");
for(;;){
Socket nextClient = server.accept();
System.out.println("Received request from " + nextClient.getInetAddress()+ ":"+ nextClient.getPort());
InputStream in = nextClient.getInputStream();
writeFile(filePath,in);
nextClient.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
*
* @param filePath
* @param in
* @throws Exception
*/
public static void writeFile(String filePath,InputStream in)throws Exception {
BufferedReader readerFile = new BufferedReader(
new InputStreamReader(in));
DataInputStream reader = new DataInputStream(in);
String filename=readerFile.readLine();
System.out.println("FileName:---------->>>>>>" + filename);
getFileName(filename);
File file=new File(filePath + FILE_NAME);
if(file.exists()){
file.delete();
System.out.println("Create new file");
}
FileOutputStream fos = new FileOutputStream(file);
byte[] bs = new byte[DATA_SIZE];
int length;
System.out.println("Data receiving started");
while( (length=reader.read(bs)) != -1){
fos.write(bs,0,length);
bs = new byte[DATA_SIZE];
Thread.sleep(200);
}
System.out.println("Receiving completed");
readerFile.close();
reader.close();
fos.close();
}
public static void getFileName(String filename)throws Exception {
FILE_NAME = filename == null?"":filename.substring(filename.lastIndexOf("\\") + 1,filename.length());
System.out.println("FILE_NAME= " + FILE_NAME);
}
}