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");
Related
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
I really dont know if how am I going to display this in my application since I just coudln't figure out if what is the exact code that i will going to use. I'm making a simple chat client server where two or more clients can chat with each other with the help of input/output streams and serversocket. what i want to do is that after a person can login it will pop up a message in JtextArea saying that a particular person is online and if the person closes the application, a message will be send to other client saying that a particular person is offline.
this is the code for ChatClient which will display a JtextArea for diplaying a mesage, JtextField for typing a message and a JButton for sending a message to the sender going back to the clients.
JTextArea incoming;
JTextArea outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
static JFrame frame;
JButton send;
JPanel mainPanel;
static String userName;
public void createAndShowGUI(){
frame = new JFrame("chat client");
mainPanel = new JPanel();
mainPanel.setBackground(new Color(53,53,53));
incoming = new JTextArea(15, 50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
//create GridBagLayout and GridBagConstraints for Layouting
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
//assign gbl inside componentPanel
mainPanel.setLayout(gbl);
//for layouting JTextArea
gbc.fill = GridBagConstraints.FIRST_LINE_START;
gbc.ipady = 0;
gbc.ipadx = 20;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.gridheight = 1;
//add labelLogin in componentPanel
gbl.setConstraints(qScroller, gbc);
mainPanel.add(qScroller);
//for layouting JTextField
outgoing = new JTextArea();
outgoing.setLineWrap(true);
outgoing.setWrapStyleWord(true);
JScrollPane oScroller = new JScrollPane(outgoing);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
oScroller.setPreferredSize(new Dimension(500,60));
gbc.fill = GridBagConstraints.FIRST_LINE_START;
gbc.ipady = 0;
gbc.ipadx = 20;
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 1;
gbc.gridheight = 0;
//add labelLogin in componentPanel
gbl.setConstraints(oScroller, gbc);
mainPanel.add(oScroller);
//instantiate JButton
send = new JButton("send");
send.addActionListener(new SendButtonListener());
send.setPreferredSize(new Dimension(48,60));
send.setBorder(BorderFactory.createEtchedBorder(1));
send.setBackground(new Color(248,181,63));
send.setFont(new Font("verdana",Font.BOLD,12));
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.LINE_START;
gbc.ipady = 0;
gbc.ipadx = 20;
gbc.gridy = 5;
gbc.gridx = 1;
gbc.gridwidth = 2;
gbc.gridheight = 0;
gbl.setConstraints(send, gbc);
mainPanel.add(send);
setUpNetworking();
//confirmation();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.add(mainPanel);
frame.setSize(605, 355);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end createAndShowGUI
private void setUpNetworking() {
try {
sock = new Socket("00.000.00.00", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("network established");
}
catch(IOException ex)
{
// ex.printStackTrace();
JOptionPane.showMessageDialog(null, "could not connect to server!","error", JOptionPane.ERROR_MESSAGE );
System.exit(0);
}
}
public String getUserName(){
return userName;
}
public void setUserName(String uname){
userName = uname;
}
//is this a right method...?
public void confirmation(){
writer.println(getUserName());
writer.flush();
//System.out.print(getUserName() + " is online " + "\n");
//incoming.append(getUserName() + " is online " + "\n");
}
public class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
writer.println(getUserName());
writer.print(" : ");
writer.println(outgoing.getText());
writer.flush();
}
catch (Exception ex) {
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
class IncomingReader implements Runnable {
LoginForm lf = new LoginForm();
public void run() {
String message;
String username;
try {
while ((username = reader.readLine()) != null) {
message = reader.readLine();
incoming.append(username + message + "\n");
//if else here?
}
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
public static void main(String [] args){
new ChatClient().createAndShowGUI();
}//end main
}//end class
below is the ChatServer where all the messages coming from the ChatClients sends to the ChatServer and send it back again so that all the clients will read the messages.
public class ChatServer {
String uname, userName, confirmation;
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSOcket) {
try {
sock = clientSOcket;
InputStreamReader isReader = new InputStreamReader(
sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void run() {
String message;
try {
// I wonder if the code below is right.?
confirmation = reader.readLine();
System.out.println(confirmation + " is online");
while ((userName = reader.readLine()) != null) {
message = reader.readLine();
// System.out.print(userName);
// System.out.print(message + "\n");
tellEveryone(userName);
tellEveryone(message);
}
} catch (Exception ex) {
System.out.println(confirmation + " is offline");
// System.out.println("connection reset!");
// ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new ChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5001);
while (true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(
clientSocket.getOutputStream());
// writer.println(confirmation);
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
hello guys i am working on program in which i have to perform a certain task after which i can close the window also.. obviously but it is not closing the window...
my main class is like
public class laudit {
public static void main(String[] arg){
SwingUtilities.invokeLater( new Runnable(){
public void run(){
JFrame frame = new mainFrame("Linux Audit");
frame.setVisible(true);
frame.setSize(700,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
Second class with panel is...following in which i am starting a ssh connection but it is not stoping as it is supposed to after completion..
public class panel extends JPanel {
String shost;
String suser;
String spass;
int sport;
public int getsport() {
return this.sport;
}
public String getshost() {
return this.shost;
}
public String getsuser() {
return this.suser;
}
public String getspass() {
return this.spass;
}
public panel(){
Dimension size = getPreferredSize();
size.width = 680;
size.height = 600;
setPreferredSize(size);
setBorder(BorderFactory.createTitledBorder("Linux Audit"));
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
JLabel labelhost = new JLabel("Host ");
JLabel labeluser = new JLabel("User name ");
JLabel labelpass = new JLabel("Password ");
JLabel labelport = new JLabel("Port ");
final JTextField host = new JTextField(15);
final JTextField user = new JTextField(15);
final JTextField pass=(JTextField)new JPasswordField(15);
final JTextField port = new JTextField(15);
final JButton start = new JButton("Start Audit");
//layout design
gc.anchor = GridBagConstraints.LINE_END;
gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx=0;
gc.gridy=0;
add(labelhost,gc);
gc.gridx=0;
gc.gridy=1;
add(labeluser,gc);
gc.gridx=0;
gc.gridy=2;
add(labelpass,gc);
gc.gridx=0;
gc.gridy=3;
add(labelport,gc);
gc.anchor = GridBagConstraints.LINE_START;
gc.gridx=1;
gc.gridy=0;
add(host,gc);
gc.gridx=1;
gc.gridy=1;
add(user,gc);
gc.gridx=1;
gc.gridy=2;
add(pass,gc);
gc.gridx=1;
gc.gridy=3;
add(port,gc);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.weighty=10;
gc.gridx=1;
gc.gridy=4;
add(start,gc);
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String shost = host.getText();
String suser = user.getText();
String spass = pass.getText();
String sportb = port.getText();
int sport = Integer.parseInt(sportb);
sshConnection s = new sshConnection();
try {
s.Connection(shost,suser,spass,sport);
} catch (JSchException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
here is the ssh connection i am very new to java programming
public class sshConnection {
public void Connection (String sHost,String sUser,String sPass,int sPort)throws JSchException, IOException{
String sshhost = sHost;
String sshuser = sUser;
String sshpass = sPass;
int sshport = sPort;
/*System.out.println(sshhost);
System.out.println(sshuser);
System.out.println(sshport);
System.out.println(sshpass);*/
String endLineStr = " # ";
JSch shell = new JSch();
// get a new session
Session session = shell.getSession(sshuser, sshhost, sshport);
// set user password and connect to a channel
session.setUserInfo(new SSHUserInfo(sshpass));
session.connect();
Channel channel = session.openChannel("shell");
channel.connect();
DataInputStream dataIn = new DataInputStream(channel.getInputStream());
DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
//file start
File f = new File("Result.txt");
if(!f.exists())
{
try {
f.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream(f);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
} catch (Exception e) {
e.printStackTrace();
} //file end
// send ls command to the server
dataOut.writeBytes("ls -la\r\n");
dataOut.flush();
// and print the response
String line = dataIn.readLine();
System.out.println(line);
while(!line.endsWith(endLineStr)) {
System.out.println(line);
line = dataIn.readLine();
}
dataIn.close();
dataOut.close();
channel.disconnect();
session.disconnect();
} }
class SSHUserInfo implements UserInfo {
private String sshpass;
SSHUserInfo(String sshpass) {
this.sshpass = sshpass;
}
public String getPassphrase() {
return null;
}
public String getPassword() {
return sshpass;
}
public boolean promptPassword(String arg0) {
return true;
}
public boolean promptPassphrase(String arg0) {
return true;
}
public boolean promptYesNo(String arg0) {
return true;
}
public void showMessage(String arg0) {
System.out.println(arg0);
}
}
Please help me out everything is working fine except this flaw...
Thanks..
The most likely cause of your problem is to do with sshConnection#Connection. This is likely blocking the Event Dispatching Thread, preventing it from processing any new events, like the window closing event.
You need to overload the connection to a seperate thread, for example...
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String shost = host.getText();
String suser = user.getText();
String spass = pass.getText();
String sportb = port.getText();
int sport = Integer.parseInt(sportb);
SSHTask task = new SSTask(shost, suser, spass, sport);
Thread thread = new Thread(task);
thread.start();
}
});
SSHTask class
public class SSHTask implements Runnable {
private String host;
private String user;
private String pass;
private int port;
public SSHTask(String host, String user, String pass, int port) {
this.host = host;
this.user = user;
this.pass = pass;
this.port = port;
}
public void run() {
sshConnection s = new sshConnection();
try {
s.Connection(host,user,pass,port);
} catch (JSchException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Take a look at Concurrency for more details.
If you are going to need to interact with the UI from this Thread, you would be better of using a SwingWorker, see Concurrency in Swing for details
Updated
If you still have problems. One other thing you could try is make the Thread a daemon thread...
SSHTask task = new SSTask(shost, suser, spass, sport);
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
This is a little harsh and there is still no guarantee that the system will exit while the you have a connection open...
I have been working on an instant messenger in only java code for a while now. I am able to get it to work only if I am running the server and the client on the same computer then they communicate. But I cant get 2 different computers to connect to the same server and communicate. I have looked at many examples and I still dont understand what needs to be changed. I will show the code below most of it can be ignored only the network part needs to be looked at. The sever connection is at the bottom of the client code. I am a beginner and I appreciate any help. Thanks.
Client Code:
import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.Date;
import java.net.*;
import java.io.*;
public class NukeChatv3 extends JFrame
{
private JTextArea showtext;
private JTextField usertext;
private String hostname;
private Socket connectionsock;
private BufferedReader serverinput;
private PrintWriter serveroutput;
private int port;
private static final long serialVersionUID = 1L;
private class entersend implements KeyListener
{
public void keyTyped ( KeyEvent e )
{
}
public void keyPressed ( KeyEvent e)
{
String text = usertext.getText();
if(e.getKeyCode()== KeyEvent.VK_ENTER)
{
if (usertext.getText().equals(""))
return;
else
{
//try{
serveroutput.println(text);
usertext.setText("");
//showtext.append("[" + ft.format(dNow) + "]" + "\n" + "UserName: " + serverdata +"\n\n");
//}
/*catch(IOException in)
{
showtext.append(in.getMessage());
}*/
}
}
else
return;
}
public void keyReleased ( KeyEvent e )
{
}
}
private class sender implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (usertext.getText().equals(""))
return;
else
{
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
String text = usertext.getText();
usertext.setText("");
//* Send message to server
showtext.append(ft.format(dNow) + "\n" + "UserName: " + text +"\n\n");
}
}
}
private class startconnection implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
clientconnection connect = new clientconnection();
connect.start();
}
}
private class CheckOnExit implements WindowListener
{
public void windowOpened(WindowEvent e)
{}
public void windowClosing(WindowEvent e)
{
ConfirmWindow checkers = new ConfirmWindow( );
checkers.setVisible(true);
}
public void windowClosed(WindowEvent e)
{}
public void windowIconified(WindowEvent e)
{}
public void windowDeiconified(WindowEvent e)
{}
public void windowActivated(WindowEvent e)
{}
public void windowDeactivated(WindowEvent e)
{}
}
private class ConfirmWindow extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
public ConfirmWindow( )
{
setSize(200, 100);
getContentPane( ).setBackground(Color.LIGHT_GRAY);
setLayout(new BorderLayout( ));
JLabel confirmLabel = new JLabel(
"Are you sure you want to exit?");
add(confirmLabel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel( );
buttonPanel.setBackground(Color.GRAY);
buttonPanel.setLayout(new FlowLayout( ));
JButton exitButton = new JButton("Yes");
exitButton.addActionListener(this);
buttonPanel.add(exitButton);
JButton cancelButton = new JButton("No");
cancelButton.addActionListener(this);
buttonPanel.add(cancelButton);
add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("Yes"))
System.exit(0);
else if (actionCommand.equals("No"))
dispose( );
else
System.out.println("Unexpected Error in Confirm Window.");
}
}
public static void main(String[] args)
{
NukeChatv3 nuke = new NukeChatv3();
nuke.setVisible(true);
}
public NukeChatv3()
{
setTitle("NukeChat v3");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setSize(550, 400);
setResizable(false);
addWindowListener(new CheckOnExit());
addWindowListener(new WindowAdapter(){
public void windowOpened(WindowEvent e){
usertext.requestFocus();
}
});
getContentPane().setBackground(Color.BLACK);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
showtext = new JTextArea(15, 35);
showtext.setEditable(false);
showtext.setLineWrap(true);
DefaultCaret caret = (DefaultCaret)showtext.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane scrollbar = new JScrollPane(showtext);
scrollbar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollbar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
c.anchor = GridBagConstraints.FIRST_LINE_START;
//c.gridwidth = 2;
c.insets = new Insets(20, 20, 20, 20);
c.weightx = .5;
c.weighty = .5;
c.gridx = 0;
c.gridy = 0;
add(scrollbar, c);
usertext = new JTextField(35);
usertext.requestFocusInWindow();
usertext.addKeyListener(new entersend());
//c.gridwidth = 1;
c.insets = new Insets(0, 20, 0, 0);
c.weightx = .5;
c.gridx = 0;
c.gridy = 1;
add(usertext, c);
JPanel empty = new JPanel();
c.gridx = 1;
c.gridy = 0;
empty.setLayout(new GridLayout(2,1));
JButton test1 = new JButton("test1");
empty.add(test1);
JButton test2 = new JButton("test2");
empty.add(test2);
add(empty, c);
JButton send = new JButton("Send");
send.addActionListener(new sender());
c.ipady = -5;
c.insets = new Insets(0, 0, 20, 0);
c.gridx = 1;
c.gridy = 1;
add(send, c);
JMenu menu = new JMenu("File");
JMenuItem connection = new JMenuItem("Connect");
connection.addActionListener(new startconnection());
menu.add(connection);
JMenuBar bar = new JMenuBar();
bar.add(menu);
setJMenuBar(bar);
}
private class clientconnection extends Thread
{
public void run()
{
try
{
// Set host name and port//
hostname = "localhost";
port = 16666;
// connect to socket of the server//
connectionsock = new Socket(hostname, port);
// set up client input from server//
serverinput = new BufferedReader(new InputStreamReader(connectionsock.getInputStream()));
// set up client output to server//
serveroutput = new PrintWriter(connectionsock.getOutputStream(), true);
// set up a looping thread to constantly check if server has sent anything
String serverdata = "";
while ((serverdata = serverinput.readLine()) != null)
{
Thread.sleep(500);
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
showtext.append("[" + ft.format(dNow) + "]" + "\n" +"Recieved from server: \n" + "UserName: " + serverdata +"\n\n");
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
catch(InterruptedException inter)
{
showtext.append("Unexpected interruption\n\n");
}
}
}
}
Server Code :
import java.net.ServerSocket;
import java.io.*;
import java.net.Socket;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class servertest extends JFrame
{
private JButton start;
private JTextArea text;
private BufferedReader clientinput;
private PrintWriter clientoutput;
private class listen implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
connection connect = new connection();
connect.start();
}
}
public servertest ()
{
setSize(400,300);
setLayout(new BorderLayout());
start = new JButton("Start");
start.addActionListener(new listen());
add(start, BorderLayout.SOUTH);
text = new JTextArea(6, 10);
text.setEditable(false);
add(text, BorderLayout.CENTER);
}
private class connection extends Thread
{
public void run()
{
try
{
// Sets up a server socket with set port//
text.setText("Waiting for connection on port 16666");
ServerSocket serversock = new ServerSocket(16666);
// Waits for the Client to connect to the server//
Socket connectionsock = serversock.accept();
// Sets up Input from the Client to go to the server//
clientinput = new BufferedReader(new InputStreamReader(connectionsock.getInputStream()));
// Sets up data output to send data from server to client//
clientoutput = new PrintWriter(connectionsock.getOutputStream(), true);
// Test server to see if it can perform a simple task//
text.setText("Connection made, waiting to client to send there name");
clientoutput.println("Enter your name please.");
// Get users name//
String clienttext = clientinput.readLine();
// Reply back to the client//
String replytext = "Welcome " + clienttext;
clientoutput.println(replytext);
text.setText("Sent: " + replytext);
while ((replytext = clientinput.readLine()) != null)
{
clientoutput.println(replytext);
text.setText("Sent: " + replytext);
}
// If you need to close the Socket connections
// clientoutput.close();
// clientinput.close();
// connetionsock.close();
// serversock.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args)
{
servertest test = new servertest();
test.setVisible(true);
}
In your client code, specify correct hostname/IP address where server is running:
private class clientconnection extends Thread
{
public void run()
{
try
{
// Set host name and port//
hostname = "localhost"; //<---- Change this to server IP address
port = 16666;
I'm working on the client side application of the client/server chat I'm doing for learning experience. My problem is I can't seem to get the socket and swing,both to run at the same time.
What I want to is, when the user opens a JOpionsPane and enters the hostname and port number, clicks okay, then they are connected. When the socket information was hardcoded it worked fine, but now I'm trying to get the users input for it.
What's meant to happen is, action listener is supposed to create the new SocketManager object that handles communication. Event though it says it's connected, it doesn't run. When I create the new SocketManager object and run it on a new thread it connects and revives messages form the server, but then the swings freezes and I have to end the process to shut it down.
Should I start it on a new worker thread or something? Maybe it's just because I'm tired, but I'm out of ideas.
EDIT
I updated my ActLis.class and SocketManager.class with the suggestion of adding a new thread for my SocketManager object 'network'. When I try and use 'network' though it returns null for some reason.
ActLis.clss
package com.client.core;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class ActLis implements ActionListener {
private Main main = new Main();;
private JTextField ipadress = new JTextField(),
portnumber = new JTextField(),
actionField;
private String username;
final JComponent[] ipinp = new JComponent[]{new JLabel("Enter Hostname (IP Adress): "),
ipadress,
new JLabel("Enter Port number: "), portnumber};
private SocketManager network;
private Window win;
public ActLis(){
}
public ActLis(JTextField t, Window w){
actionField = t;
win = w;
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if(cmd == "Exit"){
System.exit(0);
} else if(cmd == "Connect to IP"){
try{
JOptionPane.showMessageDialog(null, ipinp, "Connect to IP", JOptionPane.PLAIN_MESSAGE);
if(network != null){
network.close();
}
network = new SocketManager(ipadress.getText(),Integer.parseInt(portnumber.getText()));
network.setGUI(win);
Thread t = new Thread(network);
t.start();
JOptionPane.showMessageDialog(null, "Connected to chat host successfully!","Connected", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception ee){
JOptionPane.showMessageDialog(null, "Could not connect. Check IP adress or internet connection","Error - Could not connect", JOptionPane.ERROR_MESSAGE);
ee.printStackTrace();
}
} else if (cmd == "chatWriter"){
if( actionField.getText() != ""){
try{
network.send(actionField.getText());
win.updateChat(actionField.getText());
actionField.setText("");
actionField.requestFocus();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "You are not connected to a host. (File -> Connect to IP)","Error - Not Connected", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
} else if (cmd == "setUsername"){
username = actionField.getText();
network.send("USERNAME:" + username);
}
}
}
Main.class
package com.client.core;
import javax.swing.JFrame;
public class Main extends JFrame{
private SocketManager network;
public static void main(String[] args){
Main main = new Main();
main.run();
}
private void run(){
Window win = new Window();
win.setVisible(true);
}
}
SocketManager.class
package com.client.core;
import java.io.*;
import java.net.*;
public class SocketManager implements Runnable {
private Socket sock;
private PrintWriter output;
private BufferedReader input;
private String hostname;
private int portnumber;
private String message;
private Window gui;
public SocketManager(String ip, int port){
try{
hostname = ip;
portnumber = port;
}catch(Exception e){
System.out.println("Client: Socket failed to connect.");
}
}
public synchronized void send(String data){
try{
//System.out.println("Attempting to send: " + data);
output.println(data);
output.flush();
//System.out.println("Message sent.");
}catch(Exception e){
System.out.println("Message could not send.");
}
}
public synchronized void setGUI(Window w){
gui = w;
}
public synchronized void connect(){
try{
sock = new Socket(hostname,portnumber);
}catch(Exception e){
}
}
public synchronized Socket getSocket(){
return sock;
}
public synchronized void setSocket(SocketManager s){
sock = s.getSocket();
}
public synchronized void close(){
try{
sock.close();
}catch(Exception e){
System.out.println("Could not close connection.");
}
output = null;
input = null;
System.gc();
}
public synchronized boolean isConnected(){
return (sock == null) ? false : (sock.isConnected() && !sock.isClosed());
}
public synchronized void listenStream(){
try {
while((message = input.readLine()) != null){
System.out.println("Server: " + message);
gui.updateChat(message);
}
} catch (Exception e) {
}
}
#Override
public void run() {
try {
sock = new Socket(hostname,portnumber);
output = new PrintWriter(sock.getOutputStream(),true);
input = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
while(true){
listenStream();
}
} catch (Exception e) {
System.out.println("Run method fail. -> SocketManager.run()");
}finally{
try {
sock.close();
} catch (Exception e) {
}
}
}
}
Window.class
package com.client.core;
import java.awt.*;
import javax.swing.*;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
private SocketManager network;
private JPanel window = new JPanel(new BorderLayout()),
center = new JPanel(new BorderLayout()),
right = new JPanel(new BorderLayout()),
display = new JPanel( new BorderLayout()),
chat = new JPanel(),
users = new JPanel(new BorderLayout());
private JTextArea chatBox = new JTextArea("Welcome to the chat!", 7,50),
listOfUsers = new JTextArea("None Online");
private JTextField chatWrite = new JTextField(),
userSearch = new JTextField(10),
username = new JTextField();
private JScrollPane userList = new JScrollPane(listOfUsers),
currentChat = new JScrollPane(chatBox);
private JMenuBar menu = new JMenuBar();
private JMenu file = new JMenu("File");
private JMenuItem exit = new JMenuItem("Exit"),
ipconnect = new JMenuItem("Connect to IP");
private JComponent[] login = new JComponent[]{new JLabel("Username:"), username};
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
//Panels
listOfUsers.setLineWrap(true);
listOfUsers.setEditable(false);
display.setBackground(Color.black);
chat.setLayout(new BoxLayout(chat, BoxLayout.Y_AXIS));
chat.setBackground(Color.blue);
users.setBackground(Color.green);
//TextFields
addChatArea();
//Menu bar
addMenuBar();
//Adding the main panels.
addPanels();
//Listeners
addListeners();
for(int x = 0; x < 1; x++){
login();
}
}
private void login(){
JOptionPane.showMessageDialog(null, login, "Log in", JOptionPane.PLAIN_MESSAGE);
}
private void addChatArea(){
chatBox.setEditable(false);
userList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
currentChat.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
users.add(userList);
users.add(userSearch, BorderLayout.NORTH);
chat.add(currentChat);
chat.add(chatWrite);
chat.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
}
private void addMenuBar(){
file.add(ipconnect);
file.add(exit);
menu.add(file);
}
private void addPanels(){
right.add(users);
center.add(display, BorderLayout.CENTER);
center.add(chat, BorderLayout.SOUTH);
window.add(center, BorderLayout.CENTER);
window.add(right, BorderLayout.EAST);
window.add(menu, BorderLayout.NORTH);
add(window);
}
private void addListeners(){
username.addActionListener(new ActLis(username, this));
chatWrite.addActionListener(new ActLis(chatWrite, this));
username.setActionCommand("setUsername");
chatWrite.setActionCommand("chatWriter");
ipconnect.addActionListener(new ActLis());
exit.addActionListener(new ActLis());
}
public void setNetwork(SocketManager n){
network = n;
}
public void updateChat(String s){
chatBox.setText(chatBox.getText() + "\n" + s);
}
}
Ok #Zexanima you have create a Socket class for socket manager. Something like this:
public class YouSocketClass {
static public Socket socket = null;
static public InputStream in = null;
static public OutputStream out = null;
public YouSocketClass() {
super();
}
public static final Socket getConnection(final String ip, final int port, final int timeout) {
try {
socket = new Socket(ip, port);
try {
socket.setSoTimeout(timeout);
} catch(SocketException se) {
log("Server Timeout");
}
in = socket.getInputStream();
out = socket.getOutputStream();
} catch(ConnectException e) {
log("Server name or server ip is failed. " + e.getMessage());
e.printStackTrace();
} catch(Exception e) {
log("ERROR Socket: " + e.getMessage() + " " + e.getCause());
e.printStackTrace();
}
return socket;
}
public static void closeConnection() {
try {
if(socket != null) {
if(in != null) {
if(out != null) {
socket.close();
in.close();
out.close();
}
}
}
} catch(Exception e2) {
e2.printStackTrace();
}
}
private static Object log(Object sms) {
System.out.println("Test Socket1.0: " + sms);
return sms;
}
}
I hope that serve. :)