Java Socket need to get name of sender - java

I'm starting with Socket Server in Java. I've written already simple app where I can send text between hosts. I'm sending with my message name of the host which is sending and here is my problem, how can I get host message?
Can someone just change my code to show host name instead of message?
Here is the code:
public class FMain extends JFrame {
private JPanel contentPane = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FMain frame = new FMain();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 508, 321);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
PReceiver receiver = new PReceiver();
receiver.setBorder(new LineBorder(new Color(0, 0, 0)));
receiver.setBounds(35, 13, 423, 106);
contentPane.add(receiver);
PSender sender = new PSender((String) null, 0);
sender.setBorder(new LineBorder(new Color(0, 0, 0)));
sender.setBounds(35, 132, 423, 129);
contentPane.add(sender);
}
}
And the class which is receiving:
interface MyListener {
void messageReceived(String theLine);
}
class Receiver {
private List < MyListener > ml = new ArrayList < MyListener > ();
private Thread t = null;
private int port = 0;
private ServerSocket s = null;
private boolean end = false;
public void stop() {
t.interrupt();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void start() {
end = false;
t = new Thread(new Runnable() {
#Override
public void run() {
try {
s = new ServerSocket(port);
while (true) {
Socket sc = s.accept();
InputStream is = sc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String theLine = br.readLine();
ml.forEach((item) - > item.messageReceived(theLine));
sc.close();
}
} catch (SocketException e) {} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
public void addMyListener(MyListener m) {
ml.add(m);
}
public void removeMyListener(MyListener m) {
ml.remove(m);
}
Receiver(int port) {
this.port = port;
}
}
public class PReceiver extends JPanel implements MyListener {
private JTextField txtPort;
private Receiver r = null;
private JTextField txtMessage;
/**
* Create the panel.
*/
public PReceiver() {
setLayout(null);
txtPort = new JTextField();
txtPort.setBounds(282, 13, 62, 22);
add(txtPort);
// txtPort.setColumns(10);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(241, 16, 35, 16);
add(lblPort);
JToggleButton btnListen = new JToggleButton("Listen");
btnListen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (btnListen.isSelected()) {
r = new Receiver(Integer.parseInt(txtPort.getText()));
r.addMyListener(PReceiver.this);
r.start();
} else {
r.stop();
}
}
});
btnListen.setBounds(265, 70, 79, 25);
add(btnListen);
JLabel lblMessage = new JLabel("message");
lblMessage.setBounds(12, 51, 56, 16);
add(lblMessage);
txtMessage = new JTextField();
txtMessage.setBounds(12, 71, 220, 22);
add(txtMessage);
//txtMessage.setColumns(10);
}
#Override
public void messageReceived(String theLine) {
txtMessage.setText(theLine);
}
}
And the sender class:
class Sender {
public void send(String message, String host, int port) {
Socket s;
try {
s = new Socket(host, port);
OutputStream out = s.getOutputStream();
PrintWriter pw = new PrintWriter(out, false);
pw.println(message);
pw.flush();
pw.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class PSender extends JPanel {
private JTextField txtMessage;
private JTextField txtHost;
private JTextField txtPort;
private JLabel lblMessage;
/**
* Create the panel.
*/
public PSender(String host, int port) {
setLayout(null);
txtMessage = new JTextField();
txtMessage.setBounds(12, 77, 216, 22);
add(txtMessage);
//txtMessage.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
new Sender().send(txtMessage.getText(), txtHost.getText(), Integer.parseInt(txtPort.getText()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
});
btnSend.setBounds(268, 76, 78, 25);
add(btnSend);
txtHost = new JTextField();
txtHost.setBounds(51, 13, 149, 22);
add(txtHost);
//txtHost.setColumns(10);
txtPort = new JTextField();
txtPort.setBounds(268, 13, 78, 22);
add(txtPort);
//txtPort.setColumns(10);
JLabel lblHost = new JLabel("host:");
lblHost.setBounds(12, 16, 35, 16);
add(lblHost);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(231, 16, 35, 16);
add(lblPort);
lblMessage = new JLabel("message");
lblMessage.setBounds(12, 58, 56, 16);
add(lblMessage);
}
}

Related

Display text from one class to the GUI class

I'm new to Java and I have this code that I use to connect to a server using sockets
Client Class Code
public class Client {
Socket mysocket;
BufferedReader inFromServer;
DataOutputStream outToServer;
public Socket connect(String nameServer, int portServer) {
try
{
mysocket=new Socket(nameServer, portServer);
outToServer=new DataOutputStream(mysocket.getOutputStream());
inFromServer=new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
}
catch(UnknownHostException e)
{
System.err.println("Host error"); // Display Error
}
catch(Exception e)
{
System.out.print(e.getMessage());
System.out.print("Connection Error!"); // Display Error
System.exit(1);
}
return mysocket;
}
GUI Code
package Client;
import java.awt.EventQueue;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.SystemColor;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;
public class WindowClient {
private JFrame frmSocketConnection;
private JTextField TxtIP;
private JTextField TxtPort;
private JTextField TxtInput;
Client client = new Client();
public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WindowClient window = new WindowClient();
window.frmSocketConnection.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public WindowClient() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmSocketConnection = new JFrame();
frmSocketConnection.setTitle("Socket Connection");
frmSocketConnection.getContentPane().setBackground(Color.WHITE);
frmSocketConnection.setBounds(100, 100, 983, 633);
frmSocketConnection.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmSocketConnection.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(725, 0, 244, 596);
frmSocketConnection.getContentPane().add(panel);
panel.setLayout(null);
TxtIP = new JTextField();
TxtIP.setFont(new Font("Tahoma", Font.PLAIN, 16));
TxtIP.setBounds(10, 89, 224, 34);
panel.add(TxtIP);
TxtIP.setColumns(10);
JLabel lblIP = new JLabel("IP Address");
lblIP.setFont(new Font("Tahoma", Font.BOLD, 18));
lblIP.setHorizontalAlignment(SwingConstants.CENTER);
lblIP.setBounds(10, 45, 224, 34);
panel.add(lblIP);
TxtPort = new JTextField();
TxtPort.setFont(new Font("Tahoma", Font.PLAIN, 16));
TxtPort.setColumns(10);
TxtPort.setBounds(10, 216, 224, 34);
panel.add(TxtPort);
JLabel lblPort = new JLabel("IP Port");
lblPort.setHorizontalAlignment(SwingConstants.CENTER);
lblPort.setFont(new Font("Tahoma", Font.BOLD, 18));
lblPort.setBounds(10, 172, 224, 34);
panel.add(lblPort);
JButton btnConnect = new JButton("Connect");
btnConnect.setFocusPainted(false);
btnConnect.setBackground(SystemColor.controlHighlight);
btnConnect.setFont(new Font("Tahoma", Font.BOLD, 18));
btnConnect.setBounds(34, 317, 176, 48);
panel.add(btnConnect);
JButton btnDisconnect = new JButton("Disconnect");
btnDisconnect.setFocusPainted(false);
btnDisconnect.setEnabled(false);
btnDisconnect.setFont(new Font("Tahoma", Font.BOLD, 18));
btnDisconnect.setBackground(SystemColor.controlHighlight);
btnDisconnect.setBounds(34, 396, 176, 48);
panel.add(btnDisconnect);
TxtInput = new JTextField();
TxtInput.setFont(new Font("Tahoma", Font.PLAIN, 16));
TxtInput.setForeground(Color.WHITE);
TxtInput.setBackground(Color.DARK_GRAY);
TxtInput.setBounds(10, 547, 617, 39);
frmSocketConnection.getContentPane().add(TxtInput);
TxtInput.setColumns(10);
JButton btnEnter = new JButton("Enter");
btnEnter.setFocusPainted(false);
btnEnter.setBackground(SystemColor.controlHighlight);
btnEnter.setFont(new Font("Tahoma", Font.PLAIN, 18));
btnEnter.setBounds(623, 547, 92, 39);
frmSocketConnection.getContentPane().add(btnEnter);
JTextPane TxtConsole = new JTextPane();
StyledDocument doc = TxtConsole.getStyledDocument();
Style style = TxtConsole.addStyle("Stile", null);
TxtConsole.setFont(new Font("Monospaced", Font.PLAIN, 16));
TxtConsole.setForeground(Color.WHITE);
TxtConsole.setBackground(Color.DARK_GRAY);
TxtConsole.setBounds(10, 10, 705, 525);
frmSocketConnection.getContentPane().add(TxtConsole);
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnConnect.setEnabled(false);
btnDisconnect.setEnabled(true);
if (TxtIP.getText().length() == 0 || TxtPort.getText().length() == 0) {
StyleConstants.setForeground(style, Color.red);
try {
doc.insertString(doc.getLength(), "Error. One field is empty! \n",style);
btnConnect.setEnabled(true);
btnDisconnect.setEnabled(false);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
else if (!isNumeric(TxtPort.getText())) {
StyleConstants.setForeground(style, Color.red);
try {
doc.insertString(doc.getLength(), "The port field has to be a number! \n",style);
btnConnect.setEnabled(true);
btnDisconnect.setEnabled(false);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
else {
StyleConstants.setForeground(style, Color.white);
try {
doc.insertString(doc.getLength(), "Connection... \n",style);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
});
TxtInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TxtInput.setText("");
}
});
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDisconnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TxtIP.setText("");
TxtPort.setText("");
}
});
}
}
and I have a GUI in another class. In that class I have a JTextPane that I want to use as a "console" that display anything
This is an image of the GUI that i have at the moment
I want to display the error strings from the Client class into the JTextPane that it's in another class and I don't really know how to do it
There are many ways to communicate between data and ensure to pass it.
You can choose to throw the error/exception from Client class and ensure to catch it and put that error into the JTextPane
I could simply try this out:
public static class Client {
Socket mysocket;
BufferedReader inFromServer;
DataOutputStream outToServer;
public Socket connect(String nameServer, int portServer) throws Exception {
try
{
mysocket=new Socket(nameServer, portServer);
outToServer=new DataOutputStream(mysocket.getOutputStream());
inFromServer=new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
}
catch(UnknownHostException e)
{
throw new Exception("Unknown Host Error: " + e.getMessage());
}
catch(Exception e)
{
System.out.print("Connection Error!"); // Display Error
throw new Exception("Connection Error! " + e.getMessage());
}
return mysocket;
}
}
A very simple version would be:
Client c = new Client();
String errorMessage = "";
try {
c.connect("localhost", 8010);
} catch (Exception e) {
errorMessage = e.getMessage();
}
JTextPane pane = new JTextPane();
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setBold(attributeSet, true);
// Set the attributes before adding text
pane.setCharacterAttributes(attributeSet, true);
// A very simple version of that errorMessage for illustrations only
pane.setText(errorMessage == null ? "Welcome" : errorMessage);
In your case, if you are connecting on a button action, then:
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnConnect.setEnabled(false);
btnDisconnect.setEnabled(true);
// if-else
// ...
else {
StyleConstants.setForeground(style, Color.white);
try {
Client c = new Client();
String errorMessage = "";
try {
c.connect("localhost", 8010);
doc.insertString(doc.getLength(), "Connecting...", style);
} catch (Exception e) {
// Setting the error Message
doc.insertString(doc.getLength(), e.getMessage(), style);
}
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
});

How to make TableView with status = 1 so data stored on jtable

How to make TableView with query select * from tableXXX where status='1'
if status = 1 data shown in jtable
else if status = 0 data not shown in jtable
or how to refresh jtable after status updated from 1 to 0`
This mycode
public class ViewDapur extends JInternalFrame implements ListenerDapur, ListSelectionListener{
private static final long serialVersionUID = -1108049190501656840L;
Connection konek;
Statement state;
//private ControllerDapur controllermak,controllermin;
private ModelDapur modelmak,modelmin;
private TableModelDapur tableModelmak, tableModelmin;
private JTable table;
private JTable tablemak;
private JTable tablemin;
public JTable getInputTable(){
return table;
}
public ViewDapur() {
setSize(1320, 590);
setTitle("DATA ORDERAN TRIPLE SIX");
setMaximizable(false);
setIconifiable(true);
setClosable(true);
setResizable(true);
setFrameIcon(new ImageIcon(ViewDapur.class.getResource("/com/sun/javafx/scene/web/skin/Undo_16x16_JFX.png")));
setBorder(new MatteBorder(2, 2, 2, 2, (Color) Color.MAGENTA));
setNormalBounds(new Rectangle(20, 0, 0, 0));
//controllermak = new ControllerPramusaji();
tableModelmak = new TableModelDapur();
modelmak = new ModelDapur();
modelmak.setListener(this);
//controllermak.setModel(modelmak);
//controllermin = new ControllerPramusaji();
tableModelmin = new TableModelDapur();
modelmin = new ModelDapur();
modelmin.setListener(this);
//controllermin.setModel(modelmin);
init();
tablemak.setModel(tableModelmak);
tablemak.getTableHeader().setReorderingAllowed(false);
tablemin.setModel(tableModelmin);
tablemin.getTableHeader().setReorderingAllowed(false);
try {
loadDatabasemak();
} catch (Exception ex) {
// TODO: handle exception
}
try {
loadDatabasemin();
} catch (Exception ex) {
// TODO: handle exception
}
/* Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
viewTabelMakanan("1");
viewTabelMinuman("1");
}
});
timer.start();timer.setRepeats(false);
*/ //refreshTablemamin();
//viewTabelMakanan("1");
//viewTabelMinuman("1");
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//Timer timer = new Timer(1000, new ActionListener() {
// public void actionPerformed(ActionEvent e) {
ViewDapur frame = new ViewDapur();
frame.setVisible(true);
// }
// });
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
#SuppressWarnings({ "rawtypes", "unchecked" })
private void init(){
JPanel panel = new JPanel();
panel.setBackground(new Color(119, 136, 153));
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "......"));
getContentPane().add(panel);
panel.setLayout(null);
tablemak = new JTable();
tablemak.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"No Meja", "Menu", "Jumlah", "No Antri"
}
));
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 11, 640, 540);
panel_2.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Daftar Order Makanan"));
panel_2.setLayout(null);
panel_2.add(tablemak);
panel.add(panel_2);
JScrollPane scrollPane2 = new JScrollPane(tablemak,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setBounds(10, 26, 616, 502);
panel_2.add(scrollPane2);
scrollPane2.setViewportView(tablemak);
JPanel panel_1 = new JPanel();
panel_1.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Daftar Order Minuman"));
panel_1.setBounds(660, 11, 650, 537);
panel.add(panel_1);
panel_1.setLayout(null);
tablemin = new JTable();
tablemin.setBounds(241, 24, 0, 0);
panel_1.add(tablemin);
JScrollPane scrollPane = new JScrollPane(tablemin,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(10, 25, 627, 501);
panel_1.add(scrollPane);
scrollPane.setViewportView(tablemin);
}
private void loadDatabasemak() throws ErrorInfo, SQLException{
DAOdapur daovi = UtilGlobal.getDAOdapur();
tableModelmak.setList(daovi.selectAll());
}
private void loadDatabasemin() throws ErrorInfo, SQLException{
DAOdapur daovi = UtilGlobal.getDAOdapur();
tableModelmin.setList(daovi.selectAll2());
}
#Override
public void valueChanged(ListSelectionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDelete() {
// TODO Auto-generated method stub
}
#Override
public void onChange(ModelDapur model) {
// TODO Auto-generated method stub
}
public void refreshTablemamin() {
tablemak.revalidate();
tablemak.repaint();
tablemak.getSelectionModel().clearSelection();
tablemin.revalidate();
tablemin.repaint();
tablemin.getSelectionModel().clearSelection();
tableModelmak.fireTableDataChanged();
tableModelmin.fireTableDataChanged();
}
public void viewTabelMakanan(String status){
//mejahe="";
try {
konek = Koneksi.getKoneksi();
state = konek.createStatement();
String query = "select * from tbtrans where katmenu='MAKANAN' AND stord='"+status+"' AND stdpr='0'";
ResultSet result= state.executeQuery(query);
while(result.next()){
Dapur p = new Dapur();
p.setNokey(result.getString("nokey"));
p.setNovisitor(result.getString("novisitor"));
p.setNomeja(result.getInt("nomeja"));
p.setNoantri(result.getInt("noantri"));
p.setAddedpeg(result.getString("addedpeg"));
p.setKdmc(result.getInt("kdmc"));
p.setMncafe(result.getString("mncafe"));
p.setKatmenu(result.getString("katmenu"));
p.setQty(result.getDouble("qty"));
p.setHrg(result.getDouble("hrg"));
p.setSubtotal(result.getDouble("subtotal"));
p.setWorder(result.getString("worder"));
p.setStord(result.getInt("stord"));
p.setWsaji(result.getString("wsaji"));
p.setStdpr(result.getInt("stdpr"));
p.setStkasir(result.getInt("stkasir"));
p.setPegkasir(result.getString("pegkasir"));
tableModelmak.add(p);
tableModelmak.fireTableDataChanged();
}
}
catch(Exception e){
e.printStackTrace();
}
//Pramusaji p = new Pramusaji();
}
public void viewTabelMinuman(String status){
//mejahe="";
try {
konek = Koneksi.getKoneksi();
state = konek.createStatement();
String query = "select * from tbtrans where katmenu='MINUMAN' AND stord='"+status+"' AND stdpr='0'";
ResultSet result= state.executeQuery(query);
while(result.next()){
Dapur p = new Dapur();
p.setNokey(result.getString("nokey"));
p.setNovisitor(result.getString("novisitor"));
p.setNomeja(result.getInt("nomeja"));
p.setNoantri(result.getInt("noantri"));
p.setAddedpeg(result.getString("addedpeg"));
p.setKdmc(result.getInt("kdmc"));
p.setMncafe(result.getString("mncafe"));
p.setKatmenu(result.getString("katmenu"));
p.setQty(result.getDouble("qty"));
p.setHrg(result.getDouble("hrg"));
p.setSubtotal(result.getDouble("subtotal"));
p.setWorder(result.getString("worder"));
p.setStord(result.getInt("stord"));
p.setWsaji(result.getString("wsaji"));
p.setStdpr(result.getInt("stdpr"));
p.setStkasir(result.getInt("stkasir"));
p.setPegkasir(result.getString("pegkasir"));
tableModelmin.add(p);
tableModelmin.fireTableDataChanged();
}
}
catch(Exception e){
e.printStackTrace();
}
//Pramusaji p = new Pramusaji();
}
}

Manage multipe IP cameras at the same time

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

Buffer listener to server output ERROR

I have a problem with listening to my server output. I would like to be able to print something to the console as soon as one of the quoted command. The problem that I face is that it seems to be listening but then not go along with the rest of the program. So when I try to click on a button on my GUI, it get stuck.
public class MainFrame implements Runnable {
//declare Jpanel
private static JFrame frmHome;
// The client socket
private static Socket clientSocket = null;
// The output stream
static ObjectOutputStream os;
// The input stream
static ObjectInputStream is;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static void main(String[] args) throws IOException{
// The default port.
int portNumber = 3333;
// The default host.
String host = "localhost";
/*
* Open a socket on a given host and port. Open input and output streams.
*/
try {
clientSocket = new Socket(host, portNumber);
is = new ObjectInputStream(clientSocket.getInputStream());
os = new ObjectOutputStream(clientSocket.getOutputStream());
os.flush();
System.out
.println("CONNECTED TO SERVER\n"
+ "Now using host=" + host + ", portNumber=" + portNumber);
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host "
+ host);
}
/*
* If everything has been initialized then we want to write some data to the
* socket we have opened a connection to on the port portNumber.
*/
if (clientSocket != null && os != null && is != null) {
/* Create a thread to read from the server. */
new Thread(new MainFrame()).start();
os.writeObject("Home");
os.flush();
}
}
public void run() {
/*
* Keep on reading from the socket till we receive "Bye" from the
* server. Once we received that then we want to break.
*/
MainFrame window = new MainFrame();
MainFrame.frmHome.setVisible(true);
String responseLine;
try {
while (!closed) {
Here is where I try to create my buffer reader. The 2 commands "Modify,OK" and "AdStudent ok", are coming after other parts of the GUI have successfully performed a task.
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line;
try {
while((line = br.readLine()) != null){
if (br.readLine().contains("Modify,OK")
|| br.readLine().contains("AddSudent ok")){
System.out.println("did it");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} finally{
try {
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public MainFrame() {
initialize();
}
//function to make window visible
void setVisible() throws IOException {
main(null);
}
private void initialize() {
//Initialise Main window with 3 options.
frmHome = new JFrame();
frmHome.setTitle("Home");
frmHome.setBounds(100, 100, 300, 372);
frmHome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHome.getContentPane().setLayout(null);
frmHome.setResizable(false);
JLabel lblWelcomeToSrs = new JLabel("Welcome to SRS");
lblWelcomeToSrs.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblWelcomeToSrs.setBounds(86, 183, 112, 14);
frmHome.getContentPane().add(lblWelcomeToSrs);
//initialise all buttons and labels of window.
JButton btnAdStu = new JButton("Add a student");
btnAdStu.setBounds(10, 207, 126, 23);
btnAdStu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
AddStudentFrame adus;
try {
try {
adus = new AddStudentFrame();
adus.setVisible();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frmHome.setVisible(false);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
frmHome.getContentPane().add(btnAdStu);
JButton btnCheckStud = new JButton("Search / Modify");
btnCheckStud.setBounds(146, 207, 127, 23);
btnCheckStud.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
SearchFrame searchFrame;
searchFrame = new SearchFrame();
searchFrame.setVisible();
}
});
frmHome.getContentPane().add(btnCheckStud);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBounds(0, 0, 0, 0);
frmHome.getContentPane().add(lblNewLabel);
JLabel lblCreatedByRmi = new JLabel("Created by R\u00E9mi Tuyaerts");
lblCreatedByRmi.setBounds(147, 318, 184, 14);
frmHome.getContentPane().add(lblCreatedByRmi);
JButton btnNewButton = new JButton("Complete List of Students");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CompleteListFrame studentList = new CompleteListFrame();
studentList.setVisible();
}
});
btnNewButton.setBounds(52, 241, 184, 23);
frmHome.getContentPane().add(btnNewButton);
// wonderful pictures of his excellence design by Yasser
JLabel lblNewLabel_1 = new JLabel("");
Image img = new ImageIcon(frmHome.getClass().getResource("/michaelchung.jpg")).getImage();
lblNewLabel_1.setIcon(new ImageIcon(img));
lblNewLabel_1.setBounds(80, 11, 120, 148);
frmHome.getContentPane().add(lblNewLabel_1);
}
}

JAVA - Failed to iterate sphinx4 within swing component

I am using CMU sphinx, i am running my program but getting this error appears "Can't open microphone line with format PCM_SIGNED 16000.0 Hz, 16 bit, mono, 2 bytes/frame, big-endian not supported." Cannot start microphone. i want my program to listen voice using JButton whenever JButton clicked but i can only execute once in single button click. Next click will error as i stated above. please help me what is wrong.
This is what i am doing.
public class VoiceChat {
private static JPanel contentPane;
private static JTextField textField;
private static JTextField textField2;
private static JWindow window;
private static boolean alive = true;
private static String chatMessage;
private static boolean runTimer = true;
private static boolean OverSession = false;
private static Recognizer recognizer;
private static Microphone microphone;
public VoiceChat() {
ExecutorService executor = Executors.newFixedThreadPool(2);
FutureTask<String> CountTimer = new FutureTask<String>(
new ShowCounter());
FutureTask<String> talkMode = new FutureTask<String>(new DoTalk());
executor.submit(CountTimer);
initRecognize();
executor.submit(talkMode);
try {
System.out.println(talkMode.get(20, TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
executor.shutdownNow();
e.printStackTrace();
} finally {
executor.shutdown();
}
}
public static void initGUI()
{
window = new JWindow();
window.setBounds(100, 100, 400, 200);
window.setLocationRelativeTo(null);
window.setOpacity(0.9f);
window.setVisible(true);
textField = new JTextField();
textField.setVisible(true);
textField.setEnabled(false);
textField.setBorder(new LineBorder(new Color(139, 0, 139), 2));
textField.setFont(new Font("Tunga", Font.BOLD, 36));
textField.setBounds(138, 83, 100, 53);
window.add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("Start Talking in 10 Seconds");
lblNewLabel.setVisible(true);
lblNewLabel.setForeground(new Color(0, 0, 255));
lblNewLabel.setFont(new Font("Batang", Font.PLAIN, 14));
lblNewLabel.setBounds(90, 83, 100, 53);
window.add(lblNewLabel);
}
public static void initRecognize()
{
ConfigurationManager cm = new ConfigurationManager(
VoiceChat.class.getResource("myconfig.xml"));
recognizer = (Recognizer) cm.lookup("recognizer");
recognizer.allocate();
microphone = (Microphone) cm.lookup("microphone");
if (!microphone.startRecording()) {
System.out.println("Cannot start microphone.");
recognizer.deallocate();
microphone.stopRecording();
}
}
public static boolean isAlive() {
return alive;
}
public static void setAlive(boolean alive) {
VoiceChat.alive = alive;
}
public static boolean isRunTimer() {
return runTimer;
}
public static void setRunTimer(boolean runTimer) {
VoiceChat.runTimer = runTimer;
}
public static boolean isOverSession() {
return OverSession;
}
public static void setOverSession(boolean overSession) {
OverSession = overSession;
}
public static String getChatMessage() {
return chatMessage;
}
public static void setChatMessage(String chatMessage) {
VoiceChat.chatMessage = chatMessage;
}
static class ShowCounter implements Callable<String> {
#Override
public String call() throws Exception {
Thread.sleep(5000);
Integer timeNote = 0;
initGUI();
try {
for (int i = 0; i < 10; i++) {
if (!isRunTimer()) {
textField.setVisible(false);
window.setVisible(false);
window.dispose();
break;
}
textField.setText(" " + (10 - i) + "");
timeNote = 10 - (10 - i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
textField.setVisible(false);
window.setVisible(false);
window.dispose();
setAlive(false);
setOverSession(true);
return timeNote.toString();
}
}
static class DoTalk implements Callable<String> {
#Override
public String call() throws Exception {
String resultText = "";
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
while (isAlive()) {
Result result = recognizer.recognize();
if (result != null) {
resultText = result.getBestFinalResultNoFiller();
System.out.println((new StringBuilder())
.append("You said: ").append(resultText)
.append('\n').toString());
if (!resultText.isEmpty()) {
setRunTimer(false);
break;
}
// wordFilter.add(resultText);
} else {
System.out.println("I can't hear what you said.\n");
}
}
microphone.stopRecording();
if (recognizer.getState() == State.ALLOCATED) {
recognizer.deallocate();
}
setChatMessage(resultText);
return resultText;
}
public static void main(String[] args) {
JFrame frames = new JFrame();
frames.setTitle("Simple MultiThread");
frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frames.setBounds(100, 100, 450, 300);
frames.setResizable(false);
frames.setVisible(true);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
frames.setContentPane(contentPane);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
VoiceChat x = new VoiceChat();
System.out.println(getChatMessage());
}});
btnStart.setFont(new Font("Mangal", Font.BOLD, 16));
btnStart.setBounds(180, 166, 78, 23);
contentPane.add(btnStart);
}
}}
Thanks so much. Hope you can help me.

Categories