Video Conferencing Project in Java Source Code
#################################################################################
FEATURE
#################################################################################
1.Multi Chat(Used Threadpole)
2.P2P Chat
3.P2P Audio Chat
4.P2P Video Chat
5.Complete Automated
6.H.263 compression Video
7.raw audio
PREREQUISITE:
1. JUST INSTALL jmf-2.1.1 e
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*****/ just need to copy the client side code and run it to a pc not need any manual IP ***/
How to run :
Just run server side code in a PC and then Run Client side code to different PC.Then the work is done.
Server Side Code:
ClientListener.java
Clients.java
Main.java
MessageListener.java
ServerConstant.java
ServerManager.java
ServerMonitor.java
ServerStatusListener.java
ClientListener.java
/*Clients.java
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MessengSrserver;
public interface ClientListener
{
void signIn(String userName);
void signOut(String userNamme);
void clientStatus(String status);
void mapped(String nam,String ip);
}
/*Main.java
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MessengSrserver;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.StringTokenizer;
import static MessengSrserver.ServerConstant.*;
public class Clients implements Runnable
{
Socket client;
ObjectInputStream input;
ObjectOutputStream output;
boolean keepListening;
ServerManager serverManager;
int clientNumber;
ClientListener clientListener;
public Clients(ClientListener getClientListener,Socket getClient,ServerManager getServerManager,int getClientNumber)
{
client=getClient;
clientListener=getClientListener;
try
{
serverManager=getServerManager;
clientNumber=getClientNumber;
input = new ObjectInputStream(client.getInputStream());
output = new ObjectOutputStream(client.getOutputStream());
}
catch (IOException ex)
{
ex.printStackTrace();
}
keepListening=true;
}
public void run()
{
String message="",name="";
boolean sameName=false;
while(keepListening)
{
try
{
message = (String) input.readObject();
System.out.println("Server is receiving "+ message);
StringTokenizer tokens=new StringTokenizer(message);
String header=tokens.nextToken();
name=tokens.nextToken();
if(header.equalsIgnoreCase("login"))
{
serverManager.sendNameToAll(message);
ServerManager.clientTracker[clientNumber]=name;
for(int i=0;i<serverManager.clientNumber;i++) //Create & send users list
{
String userName=ServerManager.clientTracker[i];
if(!userName.equalsIgnoreCase(""))
{
output.writeObject("login "+userName+" "+client.getInetAddress());
System.out.print("$$"+client.getInetAddress());
output.flush();
}
}
clientListener.signIn(name);
clientListener.clientStatus(name+": is signIn , IPaddress :"+client.getInetAddress()+" ,portNumber :"+client.getPort()+" by sharma");
String ip ="";
ip += client.getInetAddress();
clientListener.mapped(name,ip);
}
else if(header.equalsIgnoreCase(DISCONNECT_STRING))
{
clientListener.signOut(name);
serverManager.sendNameToAll(message);
ServerManager.clientTracker[clientNumber]="";
keepListening=false;
}
else if(header.equalsIgnoreCase("video"))
{
String name1 = tokens.nextToken();
String rec_ip = ServerMonitor.hm.get(name1);
String sen_ip = ServerMonitor.hm.get(name);
String message1 = name+" video "+rec_ip;
System.out.println("server ip back"+message1);
serverManager.sendInfo(message1);
String messa2 = name1+" video1 "+sen_ip;
serverManager.sendInfo(messa2);
}
else
{
serverManager.sendInfo(message);
}
}
catch (IOException ex)
{
clientListener.signOut(name);
serverManager.sendNameToAll(DISCONNECT_STRING+" "+name);
ServerManager.clientTracker[clientNumber]="";
break;
}
catch (ClassNotFoundException ex)
{
}
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MessengSrserver;
import MessengSrserver.ServerManager;
import MessengSrserver.ServerMonitor;
public class Main
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
ServerManager serverManager=new ServerManager();
ServerMonitor monitor=new ServerMonitor(serverManager);
monitor.setVisible(true);
}
}
MessageListener.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MessengSrserver;
import java.io.ObjectOutputStream;
public interface MessageListener
{
void sendInfo(String message);
}
ServerConstant.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MessengSrserver;
public interface ServerConstant
{
public static final int SERVER_PORT=12345;
public static final int BACKLOG=100;
public static final int CLIENT_NUMBER=100;
public static final int MULTICAST_SENDING_PORT=5555;
public static final int MULTICAST_LISTENING_PORT=5554;
public static final String MULTICAST_ADDRESS="239.0.0.1";
public static final String DISCONNECT_STRING="DISCONNECT";
public static final String MESSAGE_SEPARATOR=" >> ";
}
ServerMonitor.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* ServerMonitor.java
*
* Created on Jan 1, 2004, 2:37:44 PM
*/
package MessengSrserver;
import java.awt.BorderLayout;
import javax.swing.DefaultListSelectionModel;
import javax.swing.ListSelectionModel;
import java.util.*;
public class ServerMonitor extends javax.swing.JFrame {
ServerManager serverManager;
ServerStatusListener statusListener;
ClientListener clientListener;
static HashMap<String,String> hm = new HashMap<String,String>();
/** Creates new form ServerMonitor */
public ServerMonitor(ServerManager getManager)
{
serverManager=getManager;
statusListener=new MyStatusListener();
clientListener=new MyClientListener();
initComponents();
createListModel();
}
void createListModel()
{
list_model=new javax.swing.DefaultListModel();
list_online_clients = new javax.swing.JList(list_model);
list_online_clients.setBorder(javax.swing.BorderFactory.createTitledBorder("ONLINE CLIENTS"));
dlsm=new DefaultListSelectionModel();
dlsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list_online_clients.setSelectionModel(dlsm);
list_panel.setLayout(new BorderLayout());
list_panel.add(list_online_clients);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
ta_monitor_clients = new javax.swing.JTextArea();
list_panel = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
but_start = new javax.swing.JButton();
but_stop = new javax.swing.JButton();
lb_status = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("H-Server");
jPanel1.setBackground(new java.awt.Color(204, 255, 204));
ta_monitor_clients.setColumns(20);
ta_monitor_clients.setEditable(false);
ta_monitor_clients.setRows(5);
ta_monitor_clients.setBorder(javax.swing.BorderFactory.createTitledBorder("MONITOR CLIENTS"));
jScrollPane1.setViewportView(ta_monitor_clients);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE)
);
javax.swing.GroupLayout list_panelLayout = new javax.swing.GroupLayout(list_panel);
list_panel.setLayout(list_panelLayout);
list_panelLayout.setHorizontalGroup(
list_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 118, Short.MAX_VALUE)
);
list_panelLayout.setVerticalGroup(
list_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 233, Short.MAX_VALUE)
);
but_start.setText("Start");
but_start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
but_startActionPerformed(evt);
}
});
but_stop.setText("Stop");
but_stop.setEnabled(false);
but_stop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
but_stopActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(but_start)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(but_stop)
.addContainerGap(259, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(but_start)
.addComponent(but_stop))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
lb_status.setFont(new java.awt.Font("Tahoma", 1, 14));
lb_status.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lb_status.setText("Server is Stoped");
lb_status.setBorder(javax.swing.BorderFactory.createTitledBorder("Server Status"));
lb_status.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(list_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(10, 10, 10))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(lb_status, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(list_panel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lb_status, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void but_startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_but_startActionPerformed
// TODO add your handling code here:
but_stop.setEnabled(true);
but_start.setEnabled(false);
serverManager.startServer(statusListener,clientListener);
}//GEN-LAST:event_but_startActionPerformed
private void but_stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_but_stopActionPerformed
// TODO add your handling code here:
serverManager.stopServer(statusListener);
but_stop.setEnabled(false);
but_start.setEnabled(true);
}//GEN-LAST:event_but_stopActionPerformed
class MyStatusListener implements ServerStatusListener
{
public void status(String message)
{
lb_status.setText(message);
}
}
class MyClientListener implements ClientListener
{
public void signIn(String userName)
{
list_model.addElement((Object)userName);
}
public void signOut(String userName)
{
list_model.removeElement((Object)userName);
}
public void clientStatus(String status)
{
ta_monitor_clients.append(status+"\n");
}
public void mapped(String nam,String ip)
{
if(hm.get(nam) == null)
{
hm.put(nam,ip);
System.out.println(nam+" "+ip);
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton but_start;
private javax.swing.JButton but_stop;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
public javax.swing.JLabel lb_status;
private javax.swing.JPanel list_panel;
public javax.swing.JTextArea ta_monitor_clients;
// End of variables declaration//GEN-END:variables
public javax.swing.DefaultListModel list_model;
public javax.swing.DefaultListSelectionModel dlsm;
public javax.swing.JList list_online_clients;
}
ServerManager.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MessengSrserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static MessengSrserver.ServerConstant.*;
public class ServerManager implements MessageListener
{
ExecutorService serverExeCutor;
ServerSocket server;
Socket clientSocket;
Clients[] client;
int clientNumber=0;
static String[] clientTracker;
String users="";
public ServerManager()
{
client=new Clients[CLIENT_NUMBER];
clientTracker=new String [CLIENT_NUMBER];
serverExeCutor=Executors.newCachedThreadPool();
}
public void startServer(ServerStatusListener statusListener,ClientListener clientListener)
{
try
{
statusListener.status("Server is Listening on port : "+SERVER_PORT);
server=new ServerSocket(SERVER_PORT,BACKLOG);
serverExeCutor.execute(new ConnectionController(statusListener,clientListener));
}
catch(IOException ioe)
{
statusListener.status("IOException occured When Server start");
}
}
public void stopServer(ServerStatusListener statusListener)
{
try
{
server.close();
statusListener.status("Server is stoped");
}
catch(SocketException ex)
{
//ex.printStackTrace();
statusListener.status("SocketException Occured When Server is going to stoped");
}
catch (IOException ioe)
{
//ioe.printStackTrace();
statusListener.status("IOException Occured When Server is going to stoped");
}
}
public void controllConnection(ServerStatusListener statusListener,ClientListener clientListener)
{
while(clientNumber<CLIENT_NUMBER)
{
try
{
clientSocket= server.accept();
client[clientNumber]=new Clients(clientListener,clientSocket,this,clientNumber);
serverExeCutor.execute(client[clientNumber]);
clientNumber++;
//System.out.println(clientNumber);
}
catch(SocketException ex)
{
ex.printStackTrace();
break;
}
catch (IOException ioe)
{
ioe.printStackTrace();
statusListener.status("Some Problem Occured When connection received");
break;
}
}
}
// for sending particular Client
public void sendInfo(String message)
{
StringTokenizer tokens=new StringTokenizer(message);
String to=tokens.nextToken();
for(int i=0;i<clientNumber;i++)
{
if(clientTracker[i].equalsIgnoreCase(to))
{
try
{
client[i].output.writeObject(message);
client[i].output.flush();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
public void sendFile(String sendTo,int file)
{
for(int i=0;i<clientNumber;i++)
{
if(clientTracker[i].equalsIgnoreCase(sendTo))
{
try
{
client[i].output.writeInt(file);
client[i].output.flush();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
// send all;
public void sendNameToAll(String message)
{
for(int i=0;i<clientNumber;i++)
{
try
{
System.out.println("Server is sending "+ message);
client[i].output.writeObject(message);
client[i].output.flush();
}
catch (IOException ex)
{}
}
}
class ConnectionController implements Runnable
{
ServerStatusListener statusListener;
ClientListener clientListener;
ConnectionController(ServerStatusListener getStatusListener,ClientListener getClientListener)
{
statusListener=getStatusListener;
clientListener=getClientListener;
}
public void run()
{
controllConnection(statusListener,clientListener);
}
}
}
ServerStatusListener.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MessengSrserver;
public interface ServerStatusListener
{
public void status(String message);
}
***************************END OF SERVER******************************************
CLIENT SIDE
ClientConstant.java
ClientListListener.java
ClientListPanel.java
ClientManager.java
ClientStatusListener.java
ClientWindowListener.java
FileReceiver.java
FileSender.java
LoginFrame.java
LogInPanel.java
Main.java
AVReceive2.java
AVTransmit2.java
MessageRecever.java
MessagingFrame.java
ClientConstant.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package messengerclient;
/**
*
* @author team3
*/
public interface ClientConstant
{
public static final String SERVER_ADDRESS="172.17.0.32";
public static final int SERVER_PORT=12345;
public static final int CLIENT_NUMBER=100;
public static final String DISCONNECT_STRING="DISCONNECT";
public static final String MESSAGE_SEPARATOR=" >> ";
}
ClientListListener.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package messengerclient;
/**
*
* @author team3
*/
public interface ClientListListener
{
void addToList(String userName);
void removeFromList(String userName);
}
ClientListPanel.java
/*ClientManager.java
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* ClientListPanel.java
*
* Created on May 31, 2010, 12:13:48 AM
*/
package messengerclient;
import java.awt.BorderLayout;
import javax.swing.DefaultListSelectionModel;
import javax.swing.ListSelectionModel;
/**
*
* @author team3
*/
public class ClientListPanel extends javax.swing.JPanel {
/** Creates new form ClientListPanel */
public ClientListPanel() {
initComponents();
createListModel();
}
void createListModel()
{
list_model=new javax.swing.DefaultListModel();
list_online_clients = new javax.swing.JList(list_model);
list_online_clients.setBorder(javax.swing.BorderFactory.createTitledBorder("Buddy List"));
dlsm=new DefaultListSelectionModel();
dlsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list_online_clients.setSelectionModel(dlsm);
this.setLayout(new BorderLayout());
this.add(list_online_clients,BorderLayout.CENTER);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 182, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 339, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
public javax.swing.DefaultListModel list_model;
public javax.swing.DefaultListSelectionModel dlsm;
public javax.swing.JList list_online_clients;
}
ClientStatusListener.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package messengerclient;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import static messengerclient.ClientConstant.*;
/**
*
* @author team3
*/
public class ClientManager
{
ExecutorService clientExecutor;
Socket clientSocket ;
boolean isConnected=false;
ObjectInputStream input;
ObjectOutputStream output;
MessageRecever messageRecever;
public ClientManager()
{
clientExecutor=Executors.newCachedThreadPool();
}
public void connect(ClientStatusListener clientStatus)
{
try
{
if(isConnected)
return;
else
{
clientSocket=new Socket(SERVER_ADDRESS,SERVER_PORT);
clientStatus.loginStatus("You r connected to :"+SERVER_ADDRESS);
isConnected=true;
}
}
catch (UnknownHostException ex)
{
clientStatus.loginStatus("No Server found");
}
catch (IOException ex)
{
clientStatus.loginStatus("No Server found");
}
}
public void disconnect(ClientStatusListener clientStatus)
{
messageRecever.stopListening();
try
{
clientStatus.loginStatus("You r no longer connected to Server");
clientSocket.close();
}
catch (IOException ex)
{
}
}
public void sendMessage(String message)
{
clientExecutor.execute(new MessageSender(message));
}
public void sendFile(String fileName)
{
clientExecutor.execute(new FileSender(fileName));
}
boolean flageoutput=true;
class MessageSender implements Runnable
{
String message;
public MessageSender(String getMessage)
{
if(flageoutput)
{
try
{
output = new ObjectOutputStream(clientSocket.getOutputStream());
output.flush();
flageoutput=false;
}
catch (IOException ex)
{
}
}
message=getMessage;
System.out.println("user is sending "+ message);
}
public void run()
{
try
{
output.writeObject(message);
output.flush();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
public void receiveMessage(ClientListListener getClientListListener ,ClientWindowListener getClientWindowListener)
{
messageRecever=new MessageRecever(clientSocket,getClientListListener, getClientWindowListener,this);
clientExecutor.execute(messageRecever);
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package messengerclient;
/**
*
* @author team3
*/
public interface ClientStatusListener
{
void loginStatus(String status);
}
ClientWindowListener.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package messengerclient;
/**
*
* @author team3
*/
public interface ClientWindowListener
{
public void openWindow(String message);
public void closeWindow(String message);
public void fileStatus(String filesStatus);
}
FileReceiver.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package messengerclient;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author team3
*/
public class FileReceiver implements Runnable
{
String address;
FileReceiver(String getAddress)
{
address=getAddress.replace('/',' ').trim();
System.out.println(address);
}
public void run()
{
try {
int filesize = 6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket(address,13267);
System.out.println("Connecting...");
// receive file
byte[] mybytearray = new byte[filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("receive sharma.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
do {
bytesRead = is.read(mybytearray, current, mybytearray.length - current);
if (bytesRead >= 0) {
current += bytesRead;
}
} while (bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end - start);
bos.close();
sock.close();
} catch (UnknownHostException ex) {
Logger.getLogger(FileReceiver.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileReceiver.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
FileSender.java
/*LoginFrame.java
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package messengerclient;
/**
*
* @author team3
*/
import java.net.*;
import java.io.*;
public class FileSender implements Runnable
{
String fileName;
FileSender(String file)
{
fileName=file;
// create socket
}
public void run()
{
try {
ServerSocket servsock = new ServerSocket(13267);
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// sendfile
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
catch (IOException ex)
{
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* LoginFrame.java
*
* Created on May 30, 2010, 11:59:04 PM
*/
package messengerclient;
import java.util.*;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.StringTokenizer;
import static messengerclient.ClientConstant.*;
/**
*
* @author team3
*/
public class LoginFrame extends javax.swing.JFrame {
/** Creates new form LoginFrame */
LogInPanel loginP;
ClientListPanel buddyList;
ClientManager clientManager;
ClientStatusListener clientStatus;
ClientListListener clientListListener;
ClientWindowListener clientWindowListener;
String userName;
int messagingFrameNo=0;
MessagingFrame [] messagingFrames;
public LoginFrame(ClientManager getClientManager)
{
clientStatus=new myClientStatus();
clientListListener=new myClientListListener();
clientWindowListener=new MyClientWindowListener();
messagingFrames=new MessagingFrame[10000];
initComponents();
clientManager=getClientManager;
myPanel.setLayout(new BorderLayout());
addLogInPanel();
}
void addLogInPanel()
{
loginP=new LogInPanel();
myPanel.add(loginP,BorderLayout.CENTER);
setVisible(true);
loginP.but_signin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
but_signinActionPerformed();
}
});
}
void addBuddyList()
{
buddyList=new ClientListPanel();
myPanel.add(buddyList,BorderLayout.CENTER);
setVisible(true);
buddyList.list_online_clients.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
if(me.getClickCount()==2)
{
String to=(String)buddyList.list_online_clients.getSelectedValue();
boolean isWindowOpen=false;
for(int i=0;i<messagingFrameNo;i++)
{
if(messagingFrames[i].to.equalsIgnoreCase(to))
{
isWindowOpen=true;
break;
}
}
if(!isWindowOpen)
{
messagingFrames[messagingFrameNo]=new MessagingFrame(to,userName,clientManager);
messagingFrames[messagingFrameNo].setVisible(true);
messagingFrameNo++;
}
}
}
});
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
myPanel = new javax.swing.JPanel();
lb_status = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
mi_sign_in = new javax.swing.JMenuItem();
mi_sign_out = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("User");
javax.swing.GroupLayout myPanelLayout = new javax.swing.GroupLayout(myPanel);
myPanel.setLayout(myPanelLayout);
myPanelLayout.setHorizontalGroup(
myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 182, Short.MAX_VALUE)
);
myPanelLayout.setVerticalGroup(
myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 314, Short.MAX_VALUE)
);
lb_status.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lb_status.setText("You r not connected to server");
jMenu1.setText("User");
mi_sign_in.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
mi_sign_in.setText("Sign In");
jMenu1.add(mi_sign_in);
mi_sign_out.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
mi_sign_out.setText("Sign Out");
mi_sign_out.setEnabled(false);
mi_sign_out.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mi_sign_outActionPerformed(evt);
}
});
jMenu1.add(mi_sign_out);
jMenuBar1.add(jMenu1);
jMenu2.setText("Help");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(myPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lb_status, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(myPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lb_status)
.addContainerGap(36, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void but_signinActionPerformed()
{
if(!loginP.tf_user_name.getText().isEmpty())
{
myPanel.remove(loginP);
clientManager.connect(clientStatus);
addBuddyList();
userName=loginP.tf_user_name.getText();
setTitle("H-Messenger ("+userName+")");
clientManager.sendMessage("login "+userName);
clientManager.receiveMessage(clientListListener, clientWindowListener);
mi_sign_in.setEnabled(false);
mi_sign_out.setEnabled(true);
}
else
javax.swing.JOptionPane.showMessageDialog(this,"Please enter your Name ");
}
private void mi_sign_outActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mi_sign_outActionPerformed
// TODO add your handling code here:
myPanel.remove(buddyList);
clientManager.sendMessage(DISCONNECT_STRING+" "+userName);
clientManager.flageoutput=true;
addLogInPanel();
mi_sign_out.setEnabled(false);
mi_sign_in.setEnabled(true);
clientManager.disconnect(clientStatus);
}//GEN-LAST:event_mi_sign_outActionPerformed
class myClientStatus implements ClientStatusListener
{
public void loginStatus(String status)
{
lb_status.setText(status);
}
}
class myClientListListener implements ClientListListener
{
public void addToList(String usersName)
{
if(!usersName.equalsIgnoreCase(userName))
{
buddyList.list_model.addElement(usersName);
}
}
public void removeFromList(String userName)
{
buddyList.list_model.removeElement(userName);
}
}
class MyClientWindowListener implements ClientWindowListener
{
public void openWindow(String message)
{
boolean isWindowOpen=false;
int openWindowNo=0;
StringTokenizer tokens=new StringTokenizer(message);
String to=tokens.nextToken();
String from=tokens.nextToken();
for(int i=0;i<messagingFrameNo;i++)
{
if(messagingFrames[i].to.equalsIgnoreCase(from))
{
isWindowOpen=true;
openWindowNo=i;
break;
}
}
if(isWindowOpen)
{
messagingFrames[openWindowNo].ta_view_message.append(message.replaceFirst(to,"")+"\n");
}
else
{
messagingFrames[messagingFrameNo]=new MessagingFrame(from,userName,clientManager);
messagingFrames[messagingFrameNo].setVisible(true);
messagingFrames[messagingFrameNo].ta_view_message.append(message.replaceFirst(to,"")+"\n");
messagingFrameNo++;
}
}
public void closeWindow(String getMessage)
{
myPanel.remove(buddyList);
addLogInPanel();
mi_sign_out.setEnabled(false);
mi_sign_in.setEnabled(true);
lb_status.setText(getMessage);
}
public void fileStatus(String filesStatus)
{
lb_status.setText(filesStatus);
}
}
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
public javax.swing.JLabel lb_status;
private javax.swing.JMenuItem mi_sign_in;
private javax.swing.JMenuItem mi_sign_out;
private javax.swing.JPanel myPanel;
// End of variables declaration//GEN-END:variables
}
LogInPanel.java
/*Main.java
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* LogInPanel.java
*
* Created on May 30, 2010, 11:35:56 PM
*/
package messengerclient;
/**
*
* @author team3
*/
public class LogInPanel extends javax.swing.JPanel {
/** Creates new form LogInPanel */
public LogInPanel() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
tf_user_name = new javax.swing.JTextField();
but_signin = new javax.swing.JButton();
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Sign In "));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("User Name :");
but_signin.setText("SignIn");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(but_signin)))
.addContainerGap(49, Short.MAX_VALUE))
.addComponent(tf_user_name, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tf_user_name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(but_signin)
.addContainerGap(18, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(167, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton but_signin;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
public javax.swing.JTextField tf_user_name;
// End of variables declaration//GEN-END:variables
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import messengerclient.ClientManager;
import messengerclient.LoginFrame;
/**
*
* @author sharma
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
ClientManager clientManager=new ClientManager();
LoginFrame loginFrame=new LoginFrame(clientManager);
loginFrame.setVisible(true);
// TODO code application logic here
}
}
MessageRecever.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package messengerclient;
import javax.media.*;
import javax.media.rtp.*;
import javax.media.rtp.event.*;
import javax.media.rtp.rtcp.*;
import javax.media.protocol.*;
import javax.media.protocol.DataSource;
import javax.media.format.AudioFormat;
import javax.media.format.VideoFormat;
import javax.media.Format;
import javax.media.format.FormatChangeEvent;
import javax.media.control.BufferControl;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import static messengerclient.ClientConstant.*;
/**
*
* @author sharma
*/
public class MessageRecever implements Runnable
{
ObjectInputStream input;
boolean keepListening=true;
ClientListListener clientListListener;
ClientWindowListener clientWindowListener;
ClientManager clientManager;
Socket clientSocket;
ExecutorService clientExecutor;
MessageRecever(Socket getClientSocket,ClientListListener getClientListListener ,ClientWindowListener getClientWindowListener,ClientManager getClientManager)
{
clientExecutor=Executors.newCachedThreadPool();
clientManager=getClientManager;
clientSocket=getClientSocket;
try
{
input = new ObjectInputStream(getClientSocket.getInputStream());
}
catch (IOException ex)
{}
clientListListener=getClientListListener;
clientWindowListener=getClientWindowListener;
}
public void run()
{
String message,name="",ips = "";
while(keepListening)
{
try
{
message = (String) input.readObject();
System.out.println("user is receiving "+ message);
StringTokenizer tokens=new StringTokenizer(message);
String header=tokens.nextToken();
if(tokens.hasMoreTokens())
name=tokens.nextToken();
if(header.equalsIgnoreCase("login"))
{
clientListListener.addToList(name);
}
else if(header.equalsIgnoreCase(DISCONNECT_STRING))
{
clientListListener.removeFromList(name);
}
else if(header.equalsIgnoreCase("server"))
{
clientWindowListener.closeWindow(message);
}
// Video
else if(name.equalsIgnoreCase("video"))
{
// clientWindowListener.fileStatus("One File is Receiving");
// String address=tokens.nextToken();
// String fileName=tokens.nextToken();
// clientExecutor.execute(new FileReceiver(address));
ips = tokens.nextToken();
String st="",pt="";
st += ips;
System.out.println("#########"+st);
String str[] = new String[2];
str[0] = st + "/20002";
str[1] = st + "/20004";
AVReceive2 avReceive= new AVReceive2(str);
//VideoTransmit vt = new VideoTransmit(new MediaLocator("vfw://0"),st,"20006");
for(int o=1;o<st.length();o++)pt += st.charAt(o);
AVTransmit2 vt = new AVTransmit2(new MediaLocator("vfw://0"),pt,"20006",null);
AVTransmit2 at = new AVTransmit2(new MediaLocator("javasound://8000"),pt,"20008",null);
at.start();
String result = vt.start();
if (!avReceive.initialize())
{
System.err.println("Failed to initialize the sessions.");
System.exit(-1);
}
try
{
while (!avReceive.isDone())
Thread.sleep(60000);
}
catch (Exception ex)
{}
if (result != null) {
System.out.println("Error : " + result);
System.exit(0);
}
System.out.println("Start transmission for 60 seconds...");
// Transmit for 60 seconds and then close the processor
// This is a safeguard when using a capture data source
// so that the capture device will be properly released
// before quitting.
// The right thing to do would be to have a GUI with a
// "Stop" button that would call stop on VideoTransmit
try {
Thread.currentThread().sleep(60000);
} catch (InterruptedException ie) {
}
// Stop the transmission
vt.stop();
// avReceive.stop();
}
else if(name.equalsIgnoreCase("video1"))
{
ips = tokens.nextToken();
String st="",pt="";
st += ips;
System.out.println("*******"+st);
for(int o=1;o<st.length();o++)pt += st.charAt(o);
//VideoTransmit vt = new VideoTransmit(new MediaLocator("vfw://0"),st,"20002");
//VideoTransmit at = new VideoTransmit(new MediaLocator("javasound://8000"),st,"20004");
AVTransmit2 vt = new AVTransmit2(new MediaLocator("vfw://0"),pt,"20002",null);
AVTransmit2 at = new AVTransmit2(new MediaLocator("javasound://8000"),pt,"20004",null);
at.start();
String result = vt.start();
if (result != null) {
System.out.println("Error : " + result);
System.exit(0);
}
System.out.println("Start transmission for 60 seconds...");
String str[] = new String[2];
str[0] = st + "/20006";
str[1] = st + "/20008";
AVReceive2 avReceive= new AVReceive2(str);
if (!avReceive.initialize())
{
System.err.println("Failed to initialize the sessions.");
System.exit(-1);
}
try
{
while (!avReceive.isDone())
Thread.sleep(60000);
}
catch (Exception ex)
{}
try {
Thread.currentThread().sleep(600000);
} catch (InterruptedException ie)
{
}
// Stop the transmission
vt.stop();
}
else
{
clientWindowListener.openWindow(message);
}
}
catch (IOException ex)
{
clientListListener.removeFromList(name);
}
catch (ClassNotFoundException ex)
{
}
}
}
void stopListening()
{
keepListening=false;
}
}
MessagingFrame.java
/*AVReceive2.java
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* MessagingFrame.java
*
* Created on Jul 28, 2010, 10:04:21 AM
*/
package messengerclient;
import javax.swing.JFileChooser;
import javax.media.*;
import javax.media.protocol.*;
import javax.media.protocol.DataSource;
import javax.media.format.*;
import javax.media.control.TrackControl;
import javax.media.control.QualityControl;
import java.util.StringTokenizer;
import java.io.ObjectInputStream;
import java.net.Socket;
/**
*
* @author team3
*/
public class MessagingFrame extends javax.swing.JFrame {
/** Creates new form MessagingFrame */
ClientManager clientManager;
String from,to;
ObjectInputStream input;
public MessagingFrame(String getto,String getfrom,ClientManager getClientManager)
{
from=getfrom;
to=getto;
initComponents();
setTitle(to);
clientManager=getClientManager;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
ta_view_message = new javax.swing.JTextArea();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
tp_write_message = new javax.swing.JTextPane();
but_send = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
but_file = new javax.swing.JButton();
tf_file = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
ta_view_message.setBackground(new java.awt.Color(254, 255, 230));
ta_view_message.setColumns(20);
ta_view_message.setEditable(false);
ta_view_message.setRows(5);
ta_view_message.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
jScrollPane1.setViewportView(ta_view_message);
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
tp_write_message.setBorder(null);
jScrollPane2.setViewportView(tp_write_message);
but_send.setText("Send");
but_send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
but_sendActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(but_send)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)
.addComponent(but_send, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Video Conferencing......", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 0, 255))); // NOI18N
but_file.setText("Video");
but_file.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
but_fileActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(but_file)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
.addComponent(tf_file, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(but_file)
.addComponent(tf_file, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(10, 10, 10))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void but_sendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_but_sendActionPerformed
// TODO add your handling code here:
sendMessage();
}//GEN-LAST:event_but_sendActionPerformed
private void but_fileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_but_fileActionPerformed
// TODO add your handling code here:
String st="/";
st += tf_file.getText();
tf_file.setText(" ");
// VideoTransmit vt = new VideoTransmit(new MediaLocator("vfw://0"),st,"20002");
// String result = vt.start();
clientManager.sendMessage("video"+" "+to +" "+from);
/* if (result != null) {
System.out.println("Error : " + result);
System.exit(0);
}
System.out.println("Start transmission for 60 seconds...");
*/
/* String str[] = new String[2];
str[0] = st + "/20006";
str[1] = st + "/20008";
AVReceive2 avReceive= new AVReceive2(str);
if (!avReceive.initialize())
{
System.err.println("Failed to initialize the sessions.");
System.exit(-1);
}
try
{
while (!avReceive.isDone())
Thread.sleep(60000);
}
catch (Exception ex)
{}
*/
// Transmit for 60 seconds and then close the processor
// This is a safeguard when using a capture data source
// so that the capture device will be properly released
// before quitting.
// The right thing to do would be to have a GUI with a
// "Stop" button that would call stop on VideoTransmit
/* try {
Thread.currentThread().sleep(600000);
} catch (InterruptedException ie) {
}
// Stop the transmission
vt.stop();
*/
}//GEN-LAST:event_but_fileActionPerformed
void sendMessage()
{
String message=to+" "+from+" : " + tp_write_message.getText();
clientManager.sendMessage(message);
tp_write_message.setText(null);
ta_view_message.append(message.replaceFirst(to,"")+"\n");
}
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton but_file;
public javax.swing.JButton but_send;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
public javax.swing.JTextArea ta_view_message;
private javax.swing.JTextField tf_file;
public javax.swing.JTextPane tp_write_message;
// End of variables declaration//GEN-END:variables
}
/**AVTransmit2.java
* @(#)AVReceive2.java
*
*
* @author sharma
* @version 1.00 2010/7/24
*/
package messengerclient;
import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.util.Vector;
import javax.media.*;
import javax.media.rtp.*;
import javax.media.rtp.event.*;
import javax.media.rtp.rtcp.*;
import javax.media.protocol.*;
import javax.media.protocol.DataSource;
import javax.media.format.AudioFormat;
import javax.media.format.VideoFormat;
import javax.media.Format;
import javax.media.format.FormatChangeEvent;
import javax.media.control.BufferControl;
/**
* AVReceive2 to receive RTP transmission using the new RTP API.
*/
public class AVReceive2 implements ReceiveStreamListener, SessionListener,ControllerListener
{
String sessions[] = null;
RTPManager mgrs[] = null;
Vector playerWindows = null;
boolean dataReceived = false;
Object dataSync = new Object();
public AVReceive2(String sessions[])
{
this.sessions = sessions;
}
protected boolean initialize()
{
try
{
InetAddress ipAddr;
SessionAddress localAddr = new SessionAddress();
SessionAddress destAddr;
mgrs = new RTPManager[sessions.length];
playerWindows = new Vector();
SessionLabel session;
// Open the RTP sessions.
for (int i = 0; i < sessions.length; i++)
{
// Parse the session addresses.
System.out.println(sessions[i]);
try
{
session = new SessionLabel(sessions[i]);
}
catch (IllegalArgumentException e)
{
System.err.println("Failed to parse the session address given: " + sessions[i]);
return false;
}
System.err.println(" - Open RTP session for: addr: " + session.addr + " port: " + session.port + " ttl: " + session.ttl);
mgrs[i] = (RTPManager) RTPManager.newInstance();
//Add SessionListener
mgrs[i].addSessionListener(this);
//Add ReceiveStreamListener
mgrs[i].addReceiveStreamListener(this);
ipAddr = InetAddress.getByName(session.addr);
if( ipAddr.isMulticastAddress())
{
// local and remote address pairs are identical:
localAddr= new SessionAddress( ipAddr, session.port, session.ttl);
destAddr = new SessionAddress( ipAddr, session.port, session.ttl);
}
else
{
localAddr= new SessionAddress( InetAddress.getLocalHost(), session.port);
destAddr = new SessionAddress( ipAddr, session.port);
}
mgrs[i].initialize( localAddr);
// You can try out some other buffer size to see
// if you can get better smoothness.
BufferControl bc =
(BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
if (bc != null)
bc.setBufferLength(350);
mgrs[i].addTarget(destAddr);
}
}
catch (Exception e)
{
System.err.println("Cannot create the RTP Session: " + e.getMessage());
return false;
}
// Wait for data to arrive before moving on.
long then = System.currentTimeMillis();
long waitingPeriod = 600000; // wait for a maximum of 30 secs.
try
{
synchronized (dataSync)
{
while (!dataReceived && System.currentTimeMillis() - then < waitingPeriod)
{
if (!dataReceived)
System.err.println(" - Waiting for RTP data to arrive...");
dataSync.wait(1000);
}
}
}
catch (Exception e)
{}
if (!dataReceived)
{
System.err.println("No RTP data was received.");
close();
return false;
}
return true;
}
public boolean isDone()
{
return playerWindows.size() == 0;
}
/**
* Close the players and the session managers.
*/
protected void close()
{
for (int i = 0; i < playerWindows.size(); i++)
{
try
{
((PlayerWindow)playerWindows.elementAt(i)).close();
}
catch (Exception e)
{}
}
playerWindows.removeAllElements();
// close the RTP session.
for (int i = 0; i < mgrs.length; i++)
{
if (mgrs[i] != null)
{
mgrs[i].removeTargets( "Closing session from AVReceive2");
mgrs[i].dispose();
mgrs[i] = null;
}
}
}
PlayerWindow find(Player p)
{
for (int i = 0; i < playerWindows.size(); i++)
{
PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
if (pw.player == p)
return pw;
}
return null;
}
PlayerWindow find(ReceiveStream strm)
{
//PlayerWindow
for (int i = 0; i < playerWindows.size(); i++)
{
PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
if (pw.stream == strm)
return pw;
}
return null;
}
/**
* SessionListener.
* SessionListener: Receives notification of changes in the state of the session.
*/
public synchronized void update(SessionEvent evt)
{
if (evt instanceof NewParticipantEvent)
{
Participant p = ((NewParticipantEvent)evt).getParticipant();
System.err.println(" - A new participant had just joined: " + p.getCNAME());
}
}
/**
* ReceiveStreamListener
* ReceiveStreamListener: Receives notification of changes in the state of
* an RTP stream thatÕs being received.
*/
public synchronized void update(ReceiveStreamEvent evt)
{
//RTPManager->Participant->ReceiveStream
RTPManager mgr = (RTPManager)evt.getSource();
Participant participant = evt.getParticipant(); // could be null.
ReceiveStream stream = evt.getReceiveStream(); // could be null.
if (evt instanceof RemotePayloadChangeEvent)
{
// Informs the RTP listener that a remote RTP sender has changed the payload
// type of a data stream.
System.err.println(" - Received an RTP PayloadChangeEvent.");
System.err.println("Sorry, cannot handle payload change.");
System.exit(0);
}
else if(evt instanceof NewReceiveStreamEvent)
{
// In RTP parlance, this means that RTP data packets have been
// received from an SSRC that had not previously been sending data.
try
{
stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
if (ctl != null)
{
System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
}
else
System.err.println(" - Recevied new RTP stream");
if (participant == null)
System.err.println(" The sender of this stream had yet to be identified.");
else
{
System.err.println(" The stream comes from: " + participant.getCNAME());
}
// create a player by passing datasource to the Media Manager
Player p = javax.media.Manager.createPlayer(ds);
if (p == null)
return;
p.addControllerListener(this);
p.realize();
PlayerWindow pw = new PlayerWindow(p, stream);
playerWindows.addElement(pw);
// Notify intialize() that a new stream had arrived.
synchronized (dataSync)
{
dataReceived = true;
dataSync.notifyAll();
}
}
catch (Exception e)
{
System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
return;
}
}
// Informs the RTP listener that a previously 'orphaned' ReceiveStream
// has been associated with an Participant.
else if (evt instanceof StreamMappedEvent)
{
if (stream != null && stream.getDataSource() != null)
{
DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
System.err.println(" - The previously unidentified stream ");
if (ctl != null)
System.err.println(" " + ctl.getFormat());
System.err.println(" had now been identified as sent by: " + participant.getCNAME());
}
}
else if (evt instanceof ByeEvent)
{
System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
PlayerWindow pw = find(stream);
if (pw != null)
{
pw.close();
playerWindows.removeElement(pw);
}
}
}
/**
* ControllerListener for the Players.
*/
public synchronized void controllerUpdate(ControllerEvent ce)
{
Player p = (Player)ce.getSourceController();
if (p == null)
return;
// Get this when the internal players are realized.
if (ce instanceof RealizeCompleteEvent)
{
PlayerWindow pw = find(p);
if (pw == null)
{
// Some strange happened.
System.err.println("Internal error!");
System.exit(-1);
}
pw.initialize();
pw.setVisible(true);
p.start();
}
if (ce instanceof ControllerErrorEvent)
{
p.removeControllerListener(this);
PlayerWindow pw = find(p);
if (pw != null)
{
pw.close();
playerWindows.removeElement(pw);
}
System.err.println("AVReceive2 internal error: " + ce);
}
}
/**
* A utility class to parse the session addresses.
* <session>: <address>/<port>/<ttl>
*/
class SessionLabel
{
public String addr = null;
public int port;
public int ttl = 1;
SessionLabel(String session) throws IllegalArgumentException
{
int off;
String portStr = null, ttlStr = null;
if (session != null && session.length() > 0)
{
while (session.length() > 1 && session.charAt(0) == '/')
session = session.substring(1);
// Now see if there's a addr specified.
off = session.indexOf('/');
if (off == -1)
{
if (!session.equals(""))
addr = session;
}
else
{
addr = session.substring(0, off);
session = session.substring(off + 1);
// Now see if there's a port specified
off = session.indexOf('/');
if (off == -1)
{
if (!session.equals(""))
portStr = session;
}
else
{
portStr = session.substring(0, off);
session = session.substring(off + 1);
// Now see if there's a ttl specified
off = session.indexOf('/');
if (off == -1)
{
if (!session.equals(""))
ttlStr = session;
}
else
{
ttlStr = session.substring(0, off);
}
}
}
}
if (addr == null)
throw new IllegalArgumentException();
if (portStr != null)
{
try
{
Integer integer = Integer.valueOf(portStr);
if (integer != null)
port = integer.intValue();
}
catch (Throwable t)
{
throw new IllegalArgumentException();
}
}
else
throw new IllegalArgumentException();
if (ttlStr != null)
{
try
{
Integer integer = Integer.valueOf(ttlStr);
if (integer != null)
ttl = integer.intValue();
}
catch (Throwable t)
{
throw new IllegalArgumentException();
}
}
}
}
/**
* GUI classes for the Player.
*/
class PlayerWindow extends Frame
{
Player player;
ReceiveStream stream;
PlayerWindow(Player p, ReceiveStream strm) {
player = p;
stream = strm;
}
public void initialize() {
add(new PlayerPanel(player));
}
public void close() {
player.close();
setVisible(false);
dispose();
}
public void addNotify() {
super.addNotify();
pack();
}
}
/**
* GUI classes for the Player.
*/
class PlayerPanel extends Panel
{
Component vc, cc;
PlayerPanel(Player p)
{
setLayout(new BorderLayout());
if ((vc = p.getVisualComponent()) != null)
add("Center", vc);
if ((cc = p.getControlPanelComponent()) != null)
add("South", cc);
}
public Dimension getPreferredSize()
{
int w = 0, h = 0;
if (vc != null)
{
Dimension size = vc.getPreferredSize();
w = size.width;
h = size.height;
}
if (cc != null)
{
Dimension size = cc.getPreferredSize();
if (w == 0)
w = size.width;
h += size.height;
}
if (w < 160)
w = 160;
return new Dimension(w, h);
}
}
/* public static void main(String argv[])
{
if (argv.length == 0)
prUsage();
AVReceive2 avReceive = new AVReceive2(argv);
if (!avReceive.initialize())
{
System.err.println("Failed to initialize the sessions.");
System.exit(-1);
}
// Check to see if AVReceive2 is done.
try
{
while (!avReceive.isDone())
Thread.sleep(1000);
}
catch (Exception e)
{}
System.err.println("Exiting AVReceive2");
}
static void prUsage()
{
System.err.println("Usage: AVReceive2 <session> <session> ...");
System.err.println(" <session>: </session></session></session></ttl></port></address><address>/<port>/<ttl>");
System.exit(0);
} */
}// end of AVReceive2
package messengerclient;
import java.awt.*;
import java.io.*;
import java.net.InetAddress;
import javax.media.*;
import javax.media.protocol.*;
import javax.media.protocol.DataSource;
import javax.media.format.*;
import javax.media.control.TrackControl;
import javax.media.control.QualityControl;
import javax.media.rtp.*;
import javax.media.rtp.rtcp.*;
import com.sun.media.rtp.*;
public class AVTransmit2 {
// Input MediaLocator
// Can be a file or http or capture source
private MediaLocator locator;
private String ipAddress;
private int portBase;
private Processor processor = null;
private RTPManager rtpMgrs[];
private DataSource dataOutput = null;
public AVTransmit2(MediaLocator locator,
String ipAddress,
String pb,
Format format) {
this.locator = locator;
this.ipAddress = ipAddress;
Integer integer = Integer.valueOf(pb);
if (integer != null)
this.portBase = integer.intValue();
}
/**
* Starts the transmission. Returns null if transmission started ok.
* Otherwise it returns a string with the reason why the setup failed.
*/
public synchronized String start() {
String result;
// Create a processor for the specified media locator
// and program it to output JPEG/RTP
result = createProcessor();
if (result != null)
return result;
// Create an RTP session to transmit the output of the
// processor to the specified IP address and port no.
result = createTransmitter();
if (result != null) {
processor.close();
processor = null;
return result;
}
// Start the transmission
processor.start();
return null;
}
/**
* Stops the transmission if already started
*/
public void stop() {
synchronized (this) {
if (processor != null) {
processor.stop();
processor.close();
processor = null;
for (int i = 0; i < rtpMgrs.length; i++) {
rtpMgrs[i].removeTargets( "Session ended.");
rtpMgrs[i].dispose();
}
}
}
}
private String createProcessor() {
if (locator == null)
return "Locator is null";
DataSource ds;
DataSource clone;
try {
ds = javax.media.Manager.createDataSource(locator);
} catch (Exception e) {
return "Couldn't create DataSource";
}
// Try to create a processor to handle the input media locator
try {
processor = javax.media.Manager.createProcessor(ds);
} catch (NoProcessorException npe) {
return "Couldn't create processor";
} catch (IOException ioe) {
return "IOException creating processor";
}
// Wait for it to configure
boolean result = waitForState(processor, Processor.Configured);
if (result == false)
return "Couldn't configure processor";
// Get the tracks from the processor
TrackControl [] tracks = processor.getTrackControls();
// Do we have atleast one track?
if (tracks == null || tracks.length < 1)
return "Couldn't find tracks in processor";
// Set the output content descriptor to RAW_RTP
// This will limit the supported formats reported from
// Track.getSupportedFormats to only valid RTP formats.
ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
processor.setContentDescriptor(cd);
Format supported[];
Format chosen;
boolean atLeastOneTrack = false;
// Program the tracks.
for (int i = 0; i < tracks.length; i++) {
Format format = tracks[i].getFormat();
if (tracks[i].isEnabled()) {
supported = tracks[i].getSupportedFormats();
// We've set the output content to the RAW_RTP.
// So all the supported formats should work with RTP.
// We'll just pick the first one.
if (supported.length > 0) {
if (supported[0] instanceof VideoFormat) {
// For video formats, we should double check the
// sizes since not all formats work in all sizes.
chosen = checkForVideoSizes(tracks[i].getFormat(),
supported[0]);
} else
chosen = supported[0];
tracks[i].setFormat(chosen);
System.err.println("Track " + i + " is set to transmit as:");
System.err.println(" " + chosen);
atLeastOneTrack = true;
} else
tracks[i].setEnabled(false);
} else
tracks[i].setEnabled(false);
}
if (!atLeastOneTrack)
return "Couldn't set any of the tracks to a valid RTP format";
// Realize the processor. This will internally create a flow
// graph and attempt to create an output datasource for JPEG/RTP
// audio frames.
result = waitForState(processor, Controller.Realized);
if (result == false)
return "Couldn't realize processor";
// Set the JPEG quality to .5.
setJPEGQuality(processor, 0.5f);
// Get the output data source of the processor
dataOutput = processor.getDataOutput();
return null;
}
/**
* Use the RTPManager API to create sessions for each media
* track of the processor.
*/
private String createTransmitter() {
// Cheated. Should have checked the type.
PushBufferDataSource pbds = (PushBufferDataSource)dataOutput;
PushBufferStream pbss[] = pbds.getStreams();
rtpMgrs = new RTPManager[pbss.length];
SessionAddress localAddr, destAddr;
InetAddress ipAddr;
SendStream sendStream;
int port;
SourceDescription srcDesList[];
for (int i = 0; i < pbss.length; i++) {
try {
rtpMgrs[i] = RTPManager.newInstance();
// The local session address will be created on the
// same port as the the target port. This is necessary
// if you use AVTransmit2 in conjunction with JMStudio.
// JMStudio assumes - in a unicast session - that the
// transmitter transmits from the same port it is receiving
// on and sends RTCP Receiver Reports back to this port of
// the transmitting host.
port = portBase + 2*i;
ipAddr = InetAddress.getByName(ipAddress);
localAddr = new SessionAddress( InetAddress.getLocalHost(),
port);
destAddr = new SessionAddress( ipAddr, port);
rtpMgrs[i].initialize( localAddr);
rtpMgrs[i].addTarget( destAddr);
System.err.println( "Created RTP session: " + ipAddress + " " + port);
sendStream = rtpMgrs[i].createSendStream(dataOutput, i);
sendStream.start();
} catch (Exception e) {
return e.getMessage();
}
}
return null;
}
/**
* For JPEG and H263, we know that they only work for particular
* sizes. So we'll perform extra checking here to make sure they
* are of the right sizes.
*/
Format checkForVideoSizes(Format original, Format supported) {
int width, height;
Dimension size = ((VideoFormat)original).getSize();
Format jpegFmt = new Format(VideoFormat.JPEG_RTP);
Format h263Fmt = new Format(VideoFormat.H263_RTP);
if (supported.matches(jpegFmt)) {
// For JPEG, make sure width and height are divisible by 8.
width = (size.width % 8 == 0 ? size.width :
(int)(size.width / 8) * 8);
height = (size.height % 8 == 0 ? size.height :
(int)(size.height / 8) * 8);
} else if (supported.matches(h263Fmt)) {
// For H.263, we only support some specific sizes.
if (size.width < 128) {
width = 128;
height = 96;
} else if (size.width < 176) {
width = 176;
height = 144;
} else {
width = 352;
height = 288;
}
} else {
// We don't know this particular format. We'll just
// leave it alone then.
return supported;
}
return (new VideoFormat(null,
new Dimension(width, height),
Format.NOT_SPECIFIED,
null,
Format.NOT_SPECIFIED)).intersects(supported);
}
/**
* Setting the encoding quality to the specified value on the JPEG encoder.
* 0.5 is a good default.
*/
void setJPEGQuality(Player p, float val) {
Control cs[] = p.getControls();
QualityControl qc = null;
VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);
// Loop through the controls to find the Quality control for
// the JPEG encoder.
for (int i = 0; i < cs.length; i++) {
if (cs[i] instanceof QualityControl &&
cs[i] instanceof Owned) {
Object owner = ((Owned)cs[i]).getOwner();
// Check to see if the owner is a Codec.
// Then check for the output format.
if (owner instanceof Codec) {
Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null);
for (int j = 0; j < fmts.length; j++) {
if (fmts[j].matches(jpegFmt)) {
qc = (QualityControl)cs[i];
qc.setQuality(val);
System.err.println("- Setting quality to " +
val + " on " + qc);
break;
}
}
}
if (qc != null)
break;
}
}
}
/****************************************************************
* Convenience methods to handle processor's state changes.
****************************************************************/
private Integer stateLock = new Integer(0);
private boolean failed = false;
Integer getStateLock() {
return stateLock;
}
void setFailed() {
failed = true;
}
private synchronized boolean waitForState(Processor p, int state) {
p.addControllerListener(new StateListener());
failed = false;
// Call the required method on the processor
if (state == Processor.Configured) {
p.configure();
} else if (state == Processor.Realized) {
p.realize();
}
// Wait until we get an event that confirms the
// success of the method, or a failure event.
// See StateListener inner class
while (p.getState() < state && !failed) {
synchronized (getStateLock()) {
try {
getStateLock().wait();
} catch (InterruptedException ie) {
return false;
}
}
}
if (failed)
return false;
else
return true;
}
/****************************************************************
* Inner Classes
****************************************************************/
class StateListener implements ControllerListener {
public void controllerUpdate(ControllerEvent ce) {
// If there was an error during configure or
// realize, the processor will be closed
if (ce instanceof ControllerClosedEvent)
setFailed();
// All controller events, send a notification
// to the waiting thread in waitForState method.
if (ce instanceof ControllerEvent) {
synchronized (getStateLock()) {
getStateLock().notifyAll();
}
}
}
}
/****************************************************************
* Sample Usage for AVTransmit2 class
****************************************************************/
/* public static void main(String [] args) {
// We need three parameters to do the transmission
// For example,
// java AVTransmit2 file:/C:/media/test.mov 129.130.131.132 42050
if (args.length < 3) {
prUsage();
}
Format fmt = null;
int i = 0;
// Create a audio transmit object with the specified params.
AVTransmit2 at = new AVTransmit2(new MediaLocator(args[i]),
args[i+1], args[i+2], fmt);
// Start the transmission
String result = at.start();
// result will be non-null if there was an error. The return
// value is a String describing the possible error. Print it.
if (result != null) {
System.err.println("Error : " + result);
System.exit(0);
}
System.err.println("Start transmission for 60 seconds...");
// Transmit for 60 seconds and then close the processor
// This is a safeguard when using a capture data source
// so that the capture device will be properly released
// before quitting.
// The right thing to do would be to have a GUI with a
// "Stop" button that would call stop on AVTransmit2
try {
Thread.currentThread().sleep(60000);
} catch (InterruptedException ie) {
}
// Stop the transmission
at.stop();
System.err.println("...transmission ended.");
System.exit(0);
}
static void prUsage() {
System.err.println("Usage: AVTransmit2 <sourceURL> <destIP> <destPortBase>");
System.err.println(" <sourceURL>: input URL or file name");
System.err.println(" <destIP>: multicast, broadcast or unicast IP address for the transmission");
System.err.println(" <destPortBase>: network port numbers for the transmission.");
System.err.println(" The first track will use the destPortBase.");
System.err.println(" The next track will use destPortBase + 2 and so on.\n");
System.exit(0);
}*/
}
Can we execute this on same system just changing port number of client and server ?
ReplyDeleteYes you can preeti, as long as ports available.
Delete