Manage multipe IP cameras at the same time - java

How I can manage multiple GoPro cameras at the same time? I want to stream three videos of three GoPro cameras at the same time and record the videos on the hard disk.
I have written a tool in Java for one GoPro and it works correctly.
Help me please!
This is the code:
public class GoProStreamer extends JFrame {
private static final String CAMERA_IP = "10.5.5.9";
private static int PORT = 8080;
private static DatagramSocket mOutgoingUdpSocket;
private Process streamingProcess;
private Process writeVideoProcess;
private KeepAliveThread mKeepAliveThread;
private JPanel contentPane;
public GoProStreamer() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(800, 10, 525, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JButton btnStop = new JButton("Stop stream");
JButton btnStart = new JButton("Start stream");
JButton btnRec = new JButton("Rec");
JButton btnStopRec = new JButton("Stop Rec");
// JButton btnZoomIn = new JButton("Zoom In sincrono");
// JButton btnZoomOut = new JButton("Zoom out sincrono");
// JButton btnZoomIn1 = new JButton("Zoom In Camera 1");
// JButton btnZoomOut1 = new JButton("Zoom out Camera 1");
// JButton btnZoomIn2 = new JButton("Zoom in Camera 2");
// JButton btnZoomOut2 = new JButton("Zoom out Camera 2");
// JButton btnZoomIn3 = new JButton("Zoom in camera 3");
// JButton btnZoomOut3 = new JButton("Zoom out Camera 3");
btnStop.setEnabled(false);
btnRec.setEnabled(false);
btnStopRec.setEnabled(false);
// btnZoomIn.setEnabled(false);
// btnZoomOut.setEnabled(false);
// btnZoomIn1.setEnabled(false);
// btnZoomOut1.setEnabled(false);
// btnZoomIn2.setEnabled(false);
// btnZoomOut2.setEnabled(false);
// btnZoomIn3.setEnabled(false);
// btnZoomOut3.setEnabled(false);
JPanel panel = new JPanel();
// JPanel panel2 = new JPanel();
// JPanel panel3 = new JPanel();
// JPanel panel4 = new JPanel();
panel.add(btnStart);
panel.add(btnStop);
panel.add(btnRec);
panel.add(btnStopRec);
// panel2.add(btnZoomIn1);
// panel3.add(btnZoomOut1);
// panel2.add(btnZoomIn2);
// panel3.add(btnZoomOut2);
// panel2.add(btnZoomIn3);
// panel3.add(btnZoomOut3);
// panel4.add(btnZoomIn);
// panel4.add(btnZoomOut);
contentPane.add(panel, BorderLayout.SOUTH);
// contentPane.add(panel2, BorderLayout.NORTH);
// contentPane.add(panel3, BorderLayout.CENTER);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
startStreamService();
keepAlive();
startStreaming();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
btnRec.setEnabled(true);
btnStopRec.setEnabled(false);
// btnZoomIn.setEnabled(true);
// btnZoomOut.setEnabled(true);
// btnZoomIn1.setEnabled(true);
// btnZoomOut1.setEnabled(true);
// btnZoomIn2.setEnabled(true);
// btnZoomOut2.setEnabled(true);
// btnZoomIn3.setEnabled(true);
// btnZoomOut3.setEnabled(true);
}
});
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
stopStreaming();
stopKeepalive();
btnStart.setEnabled(true);
btnStop.setEnabled(false);
btnRec.setEnabled(false);
btnStopRec.setEnabled(false);
}
});
btnRec.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
startRec();
btnStart.setEnabled(false);
btnStop.setEnabled(false);
btnRec.setEnabled(false);
btnStopRec.setEnabled(true);
}
});
btnStopRec.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
stopRec();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
btnRec.setEnabled(true);
btnStopRec.setEnabled(false);
}
});
}
private void startStreamService() {
HttpURLConnection localConnection = null;
try {
String str = "http://" + CAMERA_IP + "/gp/gpExec?p1=gpStreamA9&c1=restart";
localConnection = (HttpURLConnection) new URL(str).openConnection();
localConnection.addRequestProperty("Cache-Control", "no-cache");
localConnection.setConnectTimeout(5000);
localConnection.setReadTimeout(5000);
int i = localConnection.getResponseCode();
if (i >= 400) {
throw new IOException("sendGET HTTP error " + i);
}
}
catch (Exception e) {
}
if (localConnection != null) {
localConnection.disconnect();
}
}
#SuppressWarnings("static-access")
private void sendUdpCommand(int paramInt) throws SocketException, IOException {
Locale localLocale = Locale.US;
Object[] arrayOfObject = new Object[4];
arrayOfObject[0] = Integer.valueOf(0);
arrayOfObject[1] = Integer.valueOf(0);
arrayOfObject[2] = Integer.valueOf(paramInt);
arrayOfObject[3] = Double.valueOf(0.0D);
byte[] arrayOfByte = String.format(localLocale, "_GPHD_:%d:%d:%d:%1f\n", arrayOfObject).getBytes();
String str = CAMERA_IP;
int i = PORT;
DatagramPacket localDatagramPacket = new DatagramPacket(arrayOfByte, arrayOfByte.length, new InetSocketAddress(str, i));
this.mOutgoingUdpSocket.send(localDatagramPacket);
}
private void startStreaming() {
Thread threadStream = new Thread() {
#Override
public void run() {
try {
streamingProcess = Runtime.getRuntime().exec("ffmpeg-20150318-git-0f16dfd-win64-static\\bin\\ffplay -i http://10.5.5.9:8080/live/amba.m3u8");
InputStream errorStream = streamingProcess.getErrorStream();
byte[] data = new byte[1024];
int length = 0;
while ((length = errorStream.read(data, 0, data.length)) > 0) {
System.out.println(new String(data, 0, length));
System.out.println(System.currentTimeMillis());
}
} catch (IOException e) {
}
}
};
threadStream.start();
}
private void startRec() {
Thread threadRec = new Thread() {
#Override
public void run() {
try {
writeVideoProcess = Runtime.getRuntime().exec("ffmpeg-20150318-git-0f16dfd-win64-static\\bin\\ffmpeg -re -i http://10.5.5.9:8080/live/amba.m3u8 -c copy -an Video_GoPro_" + Math.random() + ".avi");
InputStream errorRec = writeVideoProcess.getErrorStream();
byte[] dataRec = new byte[1024];
int lengthRec = 0;
while ((lengthRec = errorRec.read(dataRec, 0, dataRec.length)) > 0) {
System.out.println(new String(dataRec, 0, lengthRec));
System.out.println(System.currentTimeMillis());
}
} catch (IOException e) {
}
}
};
threadRec.start();
}
private void keepAlive() {
mKeepAliveThread = new KeepAliveThread();
mKeepAliveThread.start();
}
class KeepAliveThread extends Thread {
public void run() {
try {
Thread.currentThread().setName("gopro");
if (mOutgoingUdpSocket == null) {
mOutgoingUdpSocket = new DatagramSocket();
}
while ((!Thread.currentThread().isInterrupted()) && (mOutgoingUdpSocket != null)) {
sendUdpCommand(2);
Thread.sleep(2500L);
}
}
catch (SocketException e) {
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
}
}
private void stopStreaming() {
if (streamingProcess != null) {
streamingProcess.destroy();
streamingProcess = null;
}
stopKeepalive();
mOutgoingUdpSocket.disconnect();
mOutgoingUdpSocket.close();
}
private void stopRec() {
writeVideoProcess.destroy();
writeVideoProcess = null;
}
private void stopKeepalive() {
if (mKeepAliveThread != null) {
mKeepAliveThread.interrupt();
try {
mKeepAliveThread.join(10L);
mKeepAliveThread = null;
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
GoProStreamer streamer = new GoProStreamer();
streamer.setVisible(true);
streamer.setTitle("Pannello di controllo");
}
}

IMHO, it is a physical problem : a standard wifi card can't connect to multiple wifi networks.
if you're running Windows, here is a Microsoft utilty ( http://research.microsoft.com/en-us/downloads/994abd5f-53d1-4dba-a9d8-8ba1dcccead7/ ) that seems to allow it.
Microsoft Research Virtual WiFi
Virtual WiFi helps a user connect to multiple IEEE 802.11 networks with one WiFi card. VIt works by exposing multiple virtual adapters, one for each wireless network to which connectivity is desired. Virtual WiFi uses a network hopping scheme to switch the wireless card across the desired wireless networks.
As soon as you can connect all cameras at one time, try to do one thread by camera as suggested by jjurm in comments. Keep in mind that you are limited by your bandwith according to the resolution of the stream wanted (Full HD 24fps uncompressed = 1920 * 1080 * 24 ~ 50 Mbs <=> 802.11g Wifi theoric speed ).
Hope it helps

Related

Java Swing : JTabbed for putting new component in tab

I am developing Swing Application . I create new Tab for new Log Process..Print all console statement inside it . when i place tab in tab component it get mismatched pro1 hold log2 pro2 hold log1 so i dig to much but not figure out code is follow.
ProjectExecute Event Which call to CreateNew TAb Method .
if (e.getSource() == btnExecute) {
createTab();
String s = new StringBuffer().append(ProjectOutPath).toString();
dirr = new File(s);
if (!dirr.exists()) {
}
final File tagFile = new File(dirr, projectName + ".log");
if (!tagFile.exists()) {
try {
tagFile.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
SwingWorker<Boolean, Integer> worker = new SwingWorker<Boolean, Integer>() {
#SuppressWarnings({ "unchecked", "null" })
#Override
protected Boolean doInBackground() throws Exception {
PrintStream printStream = new PrintStream(new CustomOutputStream(logTextArea, tempArea));
System.setOut(printStream);
System.setErr(printStream);
File outFile = new File(tagFile.getAbsolutePath());
FileOutputStream outFileStream = new FileOutputStream(outFile);
PrintWriter outStream = new PrintWriter(outFileStream);
try {
System.out.println("ChooserFile 1 :" + chooserFile1);
MainApp.runApp(chooserFile1);
chooserFile1 = new StringBuilder().append(chooserFile1).append("/raw_data").toString();
outStream.write(logTextArea.getText());
System.out.flush();
Runtime.getRuntime().exec("clear");
outStream.close();
printStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Thread.sleep(1000);
return true;
}
protected void done() {
try {
Component c[] = panel_tree.getComponents();
panel_tree.remove(c.length - 1);
panel_tree.add(ExomDataGUI.getTreeUpdate());
panel_tree.revalidate();
panel_tree.repaint();
scrollPane.getViewport().setView(ExomDataGUI.panel_tree);
} catch (Exception e) {
System.out.println("Exception Occured....!");
}
}
#Override
protected void process(List<Integer> chunks) {
int mostRecentValue = chunks.get(chunks.size() - 1);
countLabel.setText(Integer.toString(mostRecentValue));
}
};
worker.execute();
} else {
}
}
Create TAB method
private static JScrollPane createScroll() {
System.out.println("Creatre Scrollpane Method Called....");
JTextArea ja = new JTextArea();
String S = logTextArea.getText();
ja.setText(S);
JScrollPane JScrolling = new JScrollPane(ja);
logTextArea.setText(null);
return JScrolling;
}
public static void createTab() {
JLabel lblTitle;
if (flag == 1) {
//System.out.println("************Inside If Flag ***********");
tabbedPane1.add("", new JScrollPane(logTextArea));
Demo.add(tabbedPane1);
JTextArea JTA = new JTextArea();
String log = logTextArea.getText();
JTA.setText(log);
logTextArea.setText(null);
lblTitle= new JLabel(projectName);
flag = 0;
} else {
// System.out.println("+++++++++++++++++++Inside If Flag +++++++++++");
JScrollPane JSP = createScroll();
tabbedPane1.add("here", JSP);
lblTitle= new JLabel(projectName);
}
JPanel pnlTab = new JPanel();
pnlTab.setOpaque(false);
//JLabel lblTitle = new JLabel();
JButton btnClose = new JButton();
btnClose.setOpaque(false);
btnClose.setRolloverIcon(CLOSE_TAB_ICON);
btnClose.setRolloverEnabled(true);
btnClose.setIcon(CLOSE_TAB_ICON);
btnClose.setBorder(null);
btnClose.setFocusable(false);
pnlTab.setForeground(Color.white);
pnlTab.setBackground(Color.white);
pnlTab.add(lblTitle);
pnlTab.add(btnClose);
pnlTab.setForeground(Color.white);
tabbedPane1.setTabComponentAt(tabbedPane1.getTabCount() - 1, pnlTab);
Demo.add(tabbedPane1);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int response = JOptionPane.showConfirmDialog(null, "Do You Want To Close Tab ?");
if (response == 0)
tabbedPane1.remove(tabbedPane1.getSelectedComponent());
tabIndex--;
}
};
btnClose.addActionListener(listener);
}

Get the TCP/IP address, not localhost

I found this code in the book Java 2 : Exam Guide by Barry Boone and William R Stanek.
This code is giving me the internal IP 127.0.0.1
But I want something like 115.245.12.61.
How could I get this.
I am providing my code below
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class SingleChat extends Panel {
Socket sock;
TextArea ta_RecText;
private GridBagConstraints c;
private GridBagLayout gridBag;
private Frame frame;
private Label label;
public int port = 5001;
private TextField tf_Send;
private DataOutputStream remoteOut;
static String szUserName = "";
public static void main (String [] args){
final Frame f = new Frame("Waiting For Connection...");
String s = null;
Color fore , back;
fore = new java.awt.Color(255, 255, 255);
back = new java.awt.Color(0, 173, 232);
if (args.length > 0)
s = args[0];
SingleChat chat = new SingleChat(f);
Panel pane = new Panel(), butPane = new Panel();
Label l_Label = new Label("//RADconnect");
l_Label.setForeground(fore);
l_Label.setBackground(back);
l_Label.setFont(new java.awt.Font("Lucida Console", 0, 24));
pane.add(l_Label);
f.setForeground(fore);
f.setBackground(back);
f.add("North", pane);
f.add("Center", chat);
Button but = new Button("EXIT");
but.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
System.exit(0);
}
});
but.setBackground(fore);
but.setForeground(back);
butPane.add(but);
f.add("South", butPane);
f.setSize(450, 350);
f.show();
if (s == null){
chat.server();
}
else{
chat.client(s);
}
}
public SingleChat (Frame f){
frame = f;
frame.addWindowListener(new WindowExitHandler());
Insets insets = new Insets (10, 20, 5, 10);
gridBag = new GridBagLayout();
setLayout(gridBag);
c = new GridBagConstraints();
c.insets = insets;
c.gridx = 0;
c.gridx = 0;
label = new Label("Text To Send:");
gridBag.setConstraints(label, c);
add(label);
c.gridx = 1;
tf_Send = new TextField(40);
tf_Send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
//Intercept Messages And Send Them
String msg = tf_Send.getText();
remoteOut.writeUTF(szUserName+": "+msg);
tf_Send.setText("");
ta_RecText.append(szUserName+": "+msg+"\n");
} catch (IOException x) {
displayMsg(x.getMessage()+": Connection to Peer Lost");
}
}
});
gridBag.setConstraints(tf_Send, c);
add(tf_Send);
c.gridy = 1;
c.gridx = 0;
label = new Label("Text Recived:");
gridBag.setConstraints(label, c);
add(label);
c.gridx = 1;
ta_RecText = new TextArea(5, 40);
gridBag.setConstraints(ta_RecText, c);
add(ta_RecText);
ta_RecText.setForeground(Color.BLACK);
tf_Send.setForeground(Color.BLACK);
}
private void server(){
ServerSocket sv_Sock = null;
try {
InetAddress sv_Addr = InetAddress.getByName(null);
displayMsg("Waiting For Connection on "+sv_Addr.getHostAddress()+":"+port);
sv_Sock = new ServerSocket(port, 1);
sock = sv_Sock.accept();
displayMsg("Accepted Connection From "+sock.getInetAddress().getHostName());
remoteOut = new DataOutputStream(sock.getOutputStream());
new SingleChatRecive(this).start();
} catch (IOException x){
displayMsg(x.getMessage()+": Falied to connect to client");
}
finally {
if (sv_Sock != null){
try{
sv_Sock.close();
} catch (IOException x){
}
}
}
}
private void client(String sv_Name){
try {
if (sv_Name.equals("local")){
sv_Name = null;
}
InetAddress sv_Addr = InetAddress.getByName(sv_Name);
sock = new Socket(sv_Addr.getHostName(), port);
remoteOut = new DataOutputStream(sock.getOutputStream());
displayMsg("Connected to Server "+sv_Addr.getHostName()+":"+sock.getPort());
new SingleChatRecive(this).start();
} catch (IOException e){
displayMsg(e.getMessage()+": Failed to connect to server");
}
}
void displayMsg(String sz_Title){
frame.setTitle(sz_Title);
}
protected void finalize() throws Throwable {
try {
if (remoteOut != null){
remoteOut.close();
}
if (sock != null){
sock.close();
}
} catch (IOException e){
}
super.finalize();
}
class WindowExitHandler extends WindowAdapter{
public void windowClosing(WindowEvent e){
Window w = e.getWindow();
w.setVisible(false);
w.dispose();
System.exit(0);
}
}
void saveData(){
}
}
class SingleChatRecive extends Thread {
private SingleChat chat;
private DataInputStream remoteIn;
private boolean listening = true;
public SingleChatRecive(SingleChat chat){
this.chat = chat;
}
public synchronized void run(){
String s;
try {
remoteIn = new DataInputStream(chat.sock.getInputStream());
while (listening) {
s = remoteIn.readUTF();
chat.ta_RecText.append(s+"\n");
}
} catch (IOException e){
chat.displayMsg(e.getMessage()+": Connection to Peer Lost!");
} finally {
try {
if (remoteIn != null) {
remoteIn.close();
}
} catch (IOException e){
}
}
}
}
What changes could be done to avoid getting 127.0.0.1
THANKS
From your code:
InetAddress sv_Addr = InetAddress.getByName(null);
From the javadoc: "If the host is null then an InetAddress representing an address of the loopback interface is returned."
The IP address of the loopback interface is 127.0.0.1.
To get other IP addresses you must exchange null with a valid host name. Your local machine name could do if that is where you are running your server, but any valid host name should work.
InetAddress sv_Addr = InetAddress.getByName("myserver.mydomain.com");

Java error: java.net.BindException: Address already in use: JVM_Bindin server run class

When I run the client program I get this error. I checked to see if the port number is being used and already tried changing the port multiple times.
the server uses three classes:
the main and gui
class ServerGui extends Server implements ActionListener
{
public ServerGui() throws Exception
{
JFrame jfrm = new JFrame("Check in Desk");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(500, 500);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setVisible(true);
//menu bar
JMenuBar jmb = new JMenuBar();
JMenu jmView = new JMenu("View");
// items
JMenu jmEdit = new JMenu("Edit");
// items
JMenu jmHelp = new JMenu("Help");
// items
jmb.add(jmView);
jmb.add(jmEdit);
jmb.add(jmHelp);
//add menuBar
jfrm.setJMenuBar(jmb);
}
public void actionPerformed(ActionEvent ae)
{
String comString = ae.getActionCommand();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try{
new ServerGui();
}
catch(Exception e)
{
System.out.println(e + "damn");
}
}
});
}
}
The server class
public class Server extends Thread
{
public Server() throws IOException
{
this.start();
}
public void run()
{
try
{
while(true)
{
ServerSocket socketOnWhichToListenForClients= new ServerSocket(9876);
Socket socketBackToClient = socketOnWhichToListenForClients.accept();
new ClientHandler(socketBackToClient);
}
}
catch(Exception e)
{
System.out.println(e + "in server run class");
}
}
}
client handler
public class ClientHandler extends Thread
{
private Socket socketBackToClient;
public ClientHandler(Socket socket)
{
socketBackToClient = socket;
this.start();
}
public void run()
{
try
{
InputStream is = socketBackToClient.getInputStream();
BufferedReader message = new BufferedReader(new InputStreamReader(is));
String input = message.readLine();
System.out.println(input);
socketBackToClient.close();
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
The client gui
public class ClientGui extends Client implements ActionListener
{
//private String name = "";
public ClientGui() throws Exception
{
name = JOptionPane.showInputDialog("Enter your name.");
if(name.equals(""))
return;
JFrame jfrm = new JFrame("Check in Desk");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(300, 170);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setVisible(true);
jfrm.setResizable(false);
//buttons
Font font1 = new Font("SansSerif",Font.PLAIN, 24);
Font font2 = new Font("SansSerif",Font.PLAIN, 20);
JButton jb1 = new JButton("Help");
jb1.setPreferredSize(new Dimension(100, 100));
jfrm.add(jb1);
JButton jb2 = new JButton("Check In");
jb2.setPreferredSize(new Dimension(125, 100));
jfrm.add(jb2);
jb1.setFont(font1);
jb2.setFont(font2);
//menu bar
JMenuBar jmb = new JMenuBar();
JMenu jmTools = new JMenu("Tools");
JMenuItem jmiName = new JMenuItem("Name");
JMenuItem jmiIP = new JMenuItem("Your IP");
jmTools.add(jmiName);
jmTools.add(jmiIP);
// items
JMenu jmEdit = new JMenu("Edit");
// items
JMenu jmHelp = new JMenu("Help");
JMenuItem jmiAbout = new JMenuItem("About");
jmHelp.add(jmiAbout);
// items
jmb.add(jmTools);
jmb.add(jmEdit);
jmb.add(jmHelp);
//add menuBar
jfrm.setJMenuBar(jmb);
jmiName.addActionListener(this);
jmiIP.addActionListener(this);
jb1.addActionListener(this);
jb2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String confirmHelp = "";
String confirmCheckIn = "";
if(ae.getActionCommand().equals("Name"))
JOptionPane.showMessageDialog(null,"Your name is " + getClientName());
if(ae.getActionCommand().equals("Your IP"))
JOptionPane.showMessageDialog(null,"Your IP is " + getIpAddress());
if(ae.getActionCommand().equals("Help"))
{
confirmHelp = JOptionPane.showInputDialog("Are You Sure You Want Help?");
if(confirmHelp != null && confirmHelp.equalsIgnoreCase("yes"))
{
Help();
}
}
if(ae.getActionCommand().equals("Check In"))
{
confirmCheckIn = JOptionPane.showInputDialog("Are You Sure You Want To Check In?");
if(confirmCheckIn != null && confirmCheckIn.equalsIgnoreCase("yes"))
{
CheckIn();
}
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try{
new ClientGui();
Socket socket = new Socket(InetAddress.getLocalHost(), 9876); //new Client(); // add constructor with name or pc numb
}
catch(Exception e)
{
System.out.println("client closed");
}
}
});
}
}
The client
public class Client
{
public String name = "";
Socket clientSocket;
public Client() throws Exception
{
try
{
// clientSocket = new Socket(InetAddress.getLocalHost(), 9);
OutputStream os = clientSocket.getOutputStream();
PrintWriter pwrite = new PrintWriter(os, true);
pwrite.print("yolo");
}
catch(Exception e)
{
//System.out.println("Error cant connect"); add later
}
}
public void Help()
{
System.out.println("you pressed help");
}
public void CheckIn()
{
System.out.println("you pressed Check In");
}
public String getIpAddress()
{
String str = "";
try{
InetAddress ip = InetAddress.getLocalHost();
str = ip.toString();
}
catch(UnknownHostException e)
{
System.out.println("can not find IP address");
}
return str;
}
public String getClientName()
{
return name;
}
}
The problem is that you keep recreating the ServerSocket inside the while loop. Create it once, before the loop.
The problem is at below lines where same port is used in loop to create ServerSocket that results into below exception.
try {
while (true) {
ServerSocket socketOnWhichToListenForClients = new ServerSocket(9876);
}
} catch (Exception e) {
System.out.println(e + "in server run class");
}
Look at at the exception:
java.net.BindException: Address already in use: JVM_Bindin server run class
Don't forget to close the ServerSocket in the end. Use finally block to close it.

Java Messenger Socket

I am attempting to make a "messenger"(just for learning really) and am pretty new to Socket/ServerSocket and am currently stuck in making the networking part.
Also, I do know that the ClientNetworking isn't complete. I have tried to finish it but I am stumped.
ServerMain:
public class ServerMain extends JFrame {
int WIDTH = 480;
int HEIGHT = 320;
String writeToConsole;
JPanel mainPanel, userPanel, consolePanel;
JTabbedPane tabbedPane;
JButton launchButton;
JTextArea console;
JTextField consoleInput;
JScrollPane consoleScroll;
public ServerMain() {
super("Messenger Server");
mainPanel = new JPanel();
mainPanel.setLayout(null);
Networking();
createConsolePanel();
userPanel = new JPanel();
userPanel.setLayout(null);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(userPanel, "Users");
tabbedPane.add(consolePanel, "Console");
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ServerMain frame = new ServerMain();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
public void Networking() {
ServerNetworking net;
try {
net = new ServerNetworking();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createConsolePanel() {
consolePanel = new JPanel();
consolePanel.setLayout(null);
console = new JTextArea();
console.setFont(new Font("", Font.PLAIN, 13 + 1/2));
console.setBounds(0, 0, WIDTH, HEIGHT - 100);
console.setEditable(false);
console.setLineWrap(true);
consoleInput = new JTextField(20);
consoleInput.setBounds(0, 0, WIDTH, 25);
consoleInput.setLocation(0, 240);
consoleInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
String input = consoleInput.getText();
if(input.equalsIgnoreCase("/sendmessage")) {
//console.append(input);
console.append("Input who you would like to send the message to:");
consoleInput.setText("");
} if (input.equalsIgnoreCase("/ban")) {
console.append("Who you would like to ban");
consoleInput.setText("");
}
}
});
consolePanel.add(console);
consolePanel.add(consoleInput);
}
public void consoleWrite(String write) {
console.append(write);
}
}
ServerNetworking(Thread):
public class ServerNetworking extends Thread {
private static ServerSocket servSock;
private static final int PORT = 1234;
private static void handleClient() {
Socket link = null;
try {
link = servSock.accept();
Scanner input = new Scanner(link.getInputStream());
PrintWriter output =
new PrintWriter(link.getOutputStream(),true);
int numMessages = 0;
String message = input.nextLine();
while (!message.equals("***CLOSE***")) {
System.out.println("Message received.");
numMessages++;
output.println("Message " +
numMessages + ": " + message);
message = input.nextLine();
}
output.println(numMessages + " messages received.");
} catch(IOException ioEx) {
ioEx.printStackTrace();
} finally {
try {
System.out.println( "\n* Closing connection... *");
link.close();
} catch(IOException ioEx) {
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
public void run() {
System.out.println("Opening port...\n");
try {
servSock = new ServerSocket(PORT);
} catch(IOException ioEx) {
System.out.println("Unable to attach to port!");
System.exit(1);
} do {
handleClient();
} while (true);
}
}
ClientMain:
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane;
JSplitPane friendsPane;
JTextArea messageArea, testArea;
JTextField testField;
Box box;
public ClientMain() {
super("Messenger Client");
Networking();
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void getFriends(String username) {
}
}
ClientNetworking(Thread):
public class ClientMain extends JFrame {
int WIDTH = 640;
int HEIGHT = 480;
JTabbedPane tabbedPane;
JMenuBar topMenuBar;
JMenu userMenu, helpMenu, settingsMenu;
JRadioButtonMenuItem menuItem;
JPanel mainPanel, friendsPanel, groupsPanel, testPanel;
JLabel title;
JScrollPane consoleScrollPane;
JSplitPane friendsPane;
JTextArea messageArea, testArea;
JTextField testField;
Box box;
public ClientMain() {
super("Messenger Client");
Networking();
title = new JLabel("Client!");
title.setFont(new Font("Impact", Font.PLAIN, 32));
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.add(title);
groupsPanel = new JPanel();
groupsPanel.setLayout(null);
friendsPanel = new JPanel();
friendsPanel.setLayout(null);
testPanel = new JPanel();
testPanel.setLayout(null);
testArea = new JTextArea();
testArea.setFont(new Font("", Font.PLAIN, 13 + 1/2));
testArea.setBounds(0, 0, WIDTH, HEIGHT - 100);
testArea.setEditable(false);
testArea.setLineWrap(true);
testField = new JTextField(20);
testField.setBounds(0, 380, 640, 25);
//testField.setLocation(0, HEIGHT - 50);
testField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ClientNet net = new ClientNet();
String input = null;
input = testField.getText();
testArea.append(input);
testField.setText("");
if(input.equalsIgnoreCase("/sendmessage")) {
testArea.append("\n Input who you would like to send the message to:");
input = null;
if(input.equalsIgnoreCase("Hello")) {
net.userEntry = input;
}
}
}
});
testPanel.add(testArea);
testPanel.add(testField);
tabbedPane = new JTabbedPane();
tabbedPane.add(mainPanel, "Main");
tabbedPane.add(friendsPanel, "Friends");
tabbedPane.add(groupsPanel, "Groups");
tabbedPane.add(testPanel, "Test");
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("Something here");
userMenu.add(menuItem);
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
add(topMenuBar);
add(tabbedPane);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ClientMain frame = new ClientMain();
Insets insets = frame.getInsets();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(frame.WIDTH, frame.HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setJMenuBar(frame.topMenuBar);
}
public void Networking() {
ClientNet net;
try {
net = new ClientNet();
net.start();
} catch(Exception e) {
e.printStackTrace();
}
}
public void createMenuBar() {
topMenuBar = new JMenuBar();
userMenu = new JMenu("User");
settingsMenu = new JMenu("Settings");
helpMenu = new JMenu("Help");
menuItem = new JRadioButtonMenuItem("MenuItem");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
topMenuBar.add(userMenu, "User");
topMenuBar.add(settingsMenu, "Settings");
topMenuBar.add(helpMenu, "Help");
}
public void getFriends(String username) {
}
}
This is the error I get when I launch the server, then the client:
It shouldn't be saying "Message received" cause I don't actually send a message
Opening port...
Message received.
* Closing connection... *
Exception in thread "Thread-1" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Server.ServerNetworking.handleClient(ServerNetworking.java:29)
at Server.ServerNetworking.run(ServerNetworking.java:53)
I think the problem is the following loop in the ServerNetworking class:
while (!message.equals("***CLOSE***")) {
System.out.println("Message received.");
numMessages++;
output.println("Message " +
numMessages + ": " + message);
message = input.nextLine();
}
The problem with this code is that after recieving the complete message from the client the last line of code
message = input.nextLine();
looks for another next line from the message, but since the message has already been consumed, it throws the following exception:
NoSuchElementException - if no line was found
So before reading for the next line you need to make sure that there is next line to be read. This you can do using the
hasNextLine()
method, which will return true if there is next line otherwise false.
if(input.hasNextLine()) {
message = input.nextLine(); // read the next line
} else {
break; // exit the loop because, nothing to read left
}

How to Change Brightness of Image?

i have made an application that loads image from specific directory, loads all images in stack, when i am clicking on next button next image loads.
i have also added JSlider that change Brightness of Loaded Image but it doesn't work.
i don't know why but i am not getting exact problem.
my code :
public class PictureEditor extends JFrame
{
private static final long serialVersionUID = 6676383931562999417L;
String[] validpicturetypes = {"png", "jpg", "jpeg", "gif"};
Stack<File> pictures ;
JLabel label = new JLabel();
BufferedImage a = null;
float fval=1;
public PictureEditor()
{
JPanel panel = new JPanel();
JMenuBar menubar = new JMenuBar();
JMenu toolsmenu = new JMenu("Tools");
final JSlider slider1;
slider1 = new JSlider(JSlider.HORIZONTAL,0,4,1);
slider1.setToolTipText("Slide To Change Brightness");
slider1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
slider1.setMajorTickSpacing(1);
slider1.setPaintLabels(true);
slider1.setPaintTicks(true);
slider1.setPaintTrack(true);
slider1.setAutoscrolls(true);
slider1.setBounds(50, 55, 200, 50);
slider1.addChangeListener(new ChangeListener()
{
#Override
public void stateChanged(ChangeEvent e)
{
System.out.println("Before");
fval=slider1.getValue();
chgBrt(fval);
repaint();
}
});
TitledBorder title;
title = BorderFactory.createTitledBorder("Operations");
title.setTitleJustification(TitledBorder.LEFT);
JButton RT90 = new JButton("");
JButton RT180 = new JButton("");
JButton RTM90 = new JButton("");
JButton RTM180 = new JButton("");
JButton NEXT = new JButton("");
Image img = null;
Image imgn = null;
try
{
img = ImageIO.read(getClass().getResource("/images/images_Horizontal.png"));
imgn = ImageIO.read(getClass().getResource("/images/next12.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
RT90.setIcon(new ImageIcon(img));
RT180.setIcon(new ImageIcon(img));
RTM90.setIcon(new ImageIcon(img));
RTM180.setIcon(new ImageIcon(img));
NEXT.setIcon(new ImageIcon(imgn));
JPanel buttonPane = new JPanel();
buttonPane.add(slider1);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
buttonPane.setBorder(title);
buttonPane.add(RT90);
buttonPane.add(RT180);
buttonPane.add(RTM90);
buttonPane.add(RTM180);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
NEXT.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
nextImage();
}
});
buttonPane.add(NEXT);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
final File dir = new File("");
final JFileChooser file;
file = new JFileChooser();
file.setCurrentDirectory(dir);
file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
file.showOpenDialog(panel);
String path = file.getSelectedFile().getAbsolutePath();
System.out.println(path);
pictures= getFilesInFolder(path.toString());
Action nextpictureaction = new AbstractAction("Next Picture")
{
private static final long serialVersionUID = 2421742449531785343L;
#Override
public void actionPerformed(ActionEvent e)
{
nextImage();
}
};
setJMenuBar(menubar);
menubar.add(toolsmenu);
toolsmenu.add(nextpictureaction);
panel.add(label,BorderLayout.CENTER);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setSize(1000, 700);
setTitle("PictureEditor");
setVisible(true);
}
public Stack<File> getFilesInFolder(String startPath)
{
File startFolder = new File(startPath);
Stack<File> picturestack = new Stack<File>();
String extension;
int dotindex;
// Go through the folder
for (File file : startFolder.listFiles())
{
extension = "";
dotindex = file.getName().lastIndexOf('.'); // Get the index of the dot in the filename
if (dotindex > 0)
{
extension = file.getName().substring(dotindex + 1);
// Iterate all valid file types and check it
for (String filetype : validpicturetypes)
{
if (extension.equals(filetype))
{
picturestack.add(file);
}
}
}
}
return picturestack;
}
public void nextImage()
{
try
{
a=ImageIO.read(pictures.pop().getAbsoluteFile());
}
catch (IOException e1)
{
e1.printStackTrace();
}
final ImageIcon image = new ImageIcon(a);
label.setIcon(image);
repaint();
}
#SuppressWarnings("null")
public void chgBrt(float f)
{
Graphics g = null;
Graphics2D g2d=(Graphics2D)g;
try
{
BufferedImage dest=changeBrightness(a,(float)fval);
System.out.println("Change Bright");
int w = a.getWidth();
int h = a.getHeight();
g2d.drawImage(dest,w,h,this);
ImageIO.write(dest,"jpeg",new File("/images/dest.jpg"));
System.out.println("Image Write");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public BufferedImage changeBrightness(BufferedImage src,float val)
{
RescaleOp brighterOp = new RescaleOp(val, 0, null);
return brighterOp.filter(src,null); //filtering
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PictureEditor();
}
});
}
}
anyone who can guide me and tell me where i am wrong ??
You may be able to adapt the approach shown in this RescaleTest, which varies the scaleFactor passed to RescaleOp to a value between zero and twice the slider's maximum.

Categories