import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.*; import java.net.*; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class videoServer_v2 { public static void main(String[] args ) { final ServerFrame frame = new ServerFrame(); //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.closeServer(); System.exit(0); } }); frame.setVisible(true); } } class ServerFrame extends JFrame { /** * */ Process process=null; Process process_2=null; Process process_aux=null; ServerSocket s=null; private static final long serialVersionUID = 1L; String folderName=null; boolean status=false; String aux=null; public ServerFrame() { setSize(WIDTH, HEIGHT); setTitle("VideoTransferServer"); getContentPane().setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 0; gbc.weighty = 0; final JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); final JButton folderButton = new JButton("Carpeta..."); folderButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if(status==false) { if (evt.getSource() == folderButton) { int returnVal = fc.showOpenDialog(ServerFrame.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); //This is where a real application would open the file. saveName(file.getPath()); log("Carpeta a compartir: " + file.getPath()); } else { log("Canceló la selección de carpeta."); } } } else log("Para cambiar la carpeta, detenga el servidor."); } }); JPanel folderPanel = new JPanel(); folderPanel.add(folderButton); add(folderPanel, gbc, 0, 0, 1, 1); JButton startButton = new JButton("Start"); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { new Thread() { public void run() { if(status==false) { log("Iniciando servidor..."); startServer(); } else { log("Servidor ya ha sido iniciado."); return; } } }.start(); } }); JPanel startPanel = new JPanel(); gbc.weightx = 10; startPanel.add(startButton); add(startPanel, gbc, 1, 0, 1, 1); JButton stopButton = new JButton("Stop"); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if(status==false) log("No se ha iniciado el servidor."); else { log("Cerrando servidor..."); closeServer(); log("Servidor cerrado."); status=false; } } }); JPanel stopPanel = new JPanel(); stopPanel.add(stopButton); gbc.weightx = 0; add(stopPanel, gbc, 2, 0, 1, 1); gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 100; gbc.weightx = 0; communication = new JTextArea(); communication.setColumns(10); communication.setEditable(false); add(new JScrollPane(communication), gbc, 0, 1, 3, 1); } private void saveName(String name) { folderName = name; } /** Add a component to this frame. @param c the component to add @param gbc the grid bag constraints @param x the grid bag column @param y the grid bag row @param w the number of grid bag columns spanned @param h the number of grid bag rows spanned */ private void add(Component c, GridBagConstraints gbc, int x, int y, int w, int h) { gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = w; gbc.gridheight = h; getContentPane().add(c, gbc); } /** Sends the mail message that has been authored in the GUI. */ public void startServer() { try { if(folderName==null){ log("Falta elegir carpeta a compartir"); return; } else { log("Carpeta: " + folderName); } // establish server socket s = new ServerSocket(8189); log("Socket creado."); status=true; // wait for client connection while(true){ log("Esperando por conexiones entrantes..."); Socket incoming = s.accept( ); InetAddress inetAdd = incoming.getInetAddress(); //InetAddress localAdd = incoming.getLocalAddress(); String remoteIP = inetAdd.getHostAddress(); //String localIP = localAdd.getHostAddress(); //String remoteHostname = inetAdd.getHostName(); //log("local IP: " + localIP); log("Conexión entrante desde "+ remoteIP+ ", esperando autentificación."); BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); String line; do{ line = in.readLine(); if(line.compareTo("now")==0) { out.println( "access" ); log("Cliente ("+ remoteIP+ ") aceptado, enviando lista de archivos."); break; } else { out.println( "noaccess" ); log("Acceso denegado a cliente("+ remoteIP+ "). Esperando que se autentifique de nuevo."); } }while(true); File folder = new File(folderName); File[] listOfFiles = folder.listFiles(); int FolderCount = 0; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { FolderCount++; } } out.println(FolderCount); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { //log(listOfFiles[i].getName()); out.println(listOfFiles[i].getName()); } //else if (listOfFiles[i].isDirectory()) { //System.out.println("Directory " + listOfFiles[i].getName()); //} } //out.println("??FINISH??"); //String[] Files = new String[aux]; while(true){ String parameters[] = new String[11]; for(int i=0;i<10;i++){ line = in.readLine(); if(line!=null){ if(line.equals("DESTROY")) break; //log(line); parameters[i]=line; } } if(line==null)break; else if(line.equals("DESTROY")){ log("Cerrando conexión..."); break; } parameters[10] = remoteIP; //line = in.readLine(); File file = new File("ffserver_2.conf"); BufferedReader reader = new BufferedReader(new FileReader(file)); line = ""; String oldtext = ""; while((line = reader.readLine()) != null) { int i=checkParameter(line); switch (i) { case 1: line = "VideoSize " + parameters[0]; break; case 2: line = "VideoBitRate " + parameters[1]; break; case 3: line = "VideoBufferSize " + parameters[2]; break; case 4: line = "VideoFrameRate " + parameters[3]; break; case 5: line = parameters[4]; break; case 6: line = "AudioChannels " + parameters[5]; break; case 7: line = "AudioSampleRate " + parameters[6]; break; case 8: line = "AudioBitRate " + parameters[7]; break; case 9: line = parameters[8]; break; case 10: line = "ACL allow " + parameters[10]; break; } oldtext += line + "\n"; } reader.close(); // replace a word in a file //String newtext = oldtext.replaceAll("drink", "Love"); //To replace a line in a file //String newtext = oldtext.replaceAll("VIDEOASD", "VideoBitRate"); FileWriter writer = new FileWriter("ffserver_2.conf"); writer.write(oldtext);writer.close(); log("Archivo de configuración cambiado, lanzando server:"); log("Archivo en stream: " + parameters[9]); Runtime runTime= Runtime.getRuntime(); Runtime runTime_2= Runtime.getRuntime(); process = runTime.exec("ffserver -f ffserver_2.conf"); //log("ffmpeg -i " + folderName + "/" + parameters[9] + " http://localhost:8090/feed1.ffm"); //Thread.sleep(200); //log("ffmpeg -i " + "\" " + folderName + "/" + parameters[9] + " \"" + " http://localhost:8090/feed1.ffm"); String[] cmd = { "ffmpeg", "-i", folderName + "/" + parameters[9], "http://localhost:8090/feed1.ffm" }; process_2 = runTime_2.exec(cmd); /*BufferedReader stdInput2 = new BufferedReader(new InputStreamReader(process_2.getErrorStream())); while ((aux = stdInput2.readLine()) != null) { System.out.println(aux); }*/ boolean streamstatus = true; while(true){ line = in.readLine(); if(line==null)break; if(line.equals("NEWCONFIG")){ if(process!=null) process.destroy(); if(process_2!=null) process_2.destroy(); log("Deteniendo el stream, esperando envío de configuraciones."); break; } else if(line.equals("DESTROY")){ if(process!=null) process.destroy(); if(process_2!=null) process_2.destroy(); log("Deteniendo el stream, escuchando por nuevas conexiones."); break; } else if(line.equals("PAUSE")){ if(streamstatus){ streamstatus=false; process_aux = Runtime.getRuntime().exec("pidof -s ffmpeg"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(process_aux.getInputStream())); aux = stdInput.readLine(); stdInput.close(); if(process_aux!=null) process_aux.destroy(); Runtime.getRuntime().exec("kill -s STOP " + aux); log("Pausando el stream, esperando comandos."); continue; } } else if(line.equals("RESUME")){ if(!streamstatus){ streamstatus=true; process_aux = Runtime.getRuntime().exec("pidof -s ffmpeg"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(process_aux.getInputStream())); aux = stdInput.readLine(); stdInput.close(); if(process_aux!=null) process_aux.destroy(); Runtime.getRuntime().exec("kill -s CONT " + aux); log("Resumiendo el stream, esperando comandos."); continue; } } } if(line==null)break; else if(line.equals("DESTROY"))break; else if(line.equals("NEWCONFIG")){ continue; } } } /*if (process!=null) process.destroy(); if (process_2!=null) process_2.destroy();*/ } catch (IOException ioe) { log("Socket fue cerrado o no pudo recibir conexiones."); //ioe.printStackTrace(); } } protected static int checkParameter(String aLine){ //use a second Scanner to parse the content of each line if(aLine.regionMatches(0, "VideoSize", 0, 9)==true) return 1; else if(aLine.regionMatches(0, "VideoBitRate", 0, 12)==true) return 2; else if(aLine.regionMatches(0, "VideoBufferSize", 0, 15)==true) return 3; else if(aLine.regionMatches(0, "VideoFrameRate", 0, 14)==true) return 4; else if(aLine.regionMatches(0, "NoVideo", 0, 7)==true) return 5; else if(aLine.regionMatches(0, "#NoVideo", 0, 8)==true) return 5; else if(aLine.regionMatches(0, "AudioChannels", 0, 13)==true) return 6; else if(aLine.regionMatches(0, "AudioSampleRate", 0, 15)==true) return 7; else if(aLine.regionMatches(0, "AudioBitRate", 0, 12)==true) return 8; else if(aLine.regionMatches(0, "NoAudio", 0, 7)==true) return 9; else if(aLine.regionMatches(0, "#NoAudio", 0, 7)==true) return 9; else if(aLine.regionMatches(0, "ACL allow localhost", 0 ,19)==true) return 0; else if(aLine.regionMatches(0, "ACL allow", 0 ,9)==true) return 10; return 0; } public void closeServer() { if(process!=null) process.destroy(); if(process_2!=null) process_2.destroy(); if(s!=null) try { s.close(); } catch (IOException e) { log("Error al cerrar el socket."); } //else log("No se ha abierto el socket."); } public void log(String s) { communication.append(s); communication.append("\n"); } private JTextArea communication; public static final int WIDTH = 400; public static final int HEIGHT = 400; }