Creating a client-server application to echo what the user sends - java

I am creating a simple client server application in which there is a GUI client where the user can enter some text and the server will send the text back along with the time stamp.
The problem is that whenever I click on the Echo button, I get a Connection Reset error message. I have no idea why that is happening.
Here is the code:
Server
package echo;
import java.net.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class Server extends Thread{
final int PORT = 444;
ServerSocket serverSocket;
Socket socket;
InputStreamReader ir;
BufferedReader b;
PrintStream p;
Date currentTime;
Format fmt;
//------------------------------------------------------------------------------
public static void main(String[] args) {
Server s = new Server();
s.start();
}
//------------------------------------------------------------------------------
public void setupConnection(){
try{
serverSocket = new ServerSocket(PORT);
socket = serverSocket.accept();
ir = new InputStreamReader(socket.getInputStream());
b = new BufferedReader(ir);
p = new PrintStream(socket.getOutputStream());
fmt = DateFormat.getDateTimeInstance();
}catch(Exception e){
e.printStackTrace();
}
}
//------------------------------------------------------------------------------
public Server(){
}
//------------------------------------------------------------------------------
#Override
public void run(){
setupConnection();
if(socket!=null){
try {
String message = b.readLine();
if(message!=null){
p.println(fmt.format(new Date()) + " " + message);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Client
package echo;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.*;
public class Client extends JFrame{
final int PORT = 444;
Socket s;
InputStreamReader ir;
BufferedReader b;
PrintStream p;
JTextArea textArea;
JTextField field;
JScrollPane pane;
JButton echo;
//------------------------------------------------------------------------------
public static void main(String[] args) {
new Client();
}
//------------------------------------------------------------------------------
public Client(){
setupConnection();
setupGUI();
addListeners();
}
//------------------------------------------------------------------------------
public void setupConnection(){
try {
s = new Socket("localhost",PORT);
ir = new InputStreamReader(s.getInputStream());
b = new BufferedReader(ir);
p = new PrintStream(s.getOutputStream());
p.println("User Logged In");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//------------------------------------------------------------------------------
public void setupGUI(){
setLayout(new GridBagLayout());
textArea = new JTextArea(30,30);
field = new JTextField(10);
pane = new JScrollPane(textArea);
echo = new JButton("Echo");
GridBagConstraints gbc = new GridBagConstraints();
textArea.setBorder(BorderFactory.createTitledBorder("Replies from server: "));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 5;
gbc.gridheight = 5;
add(pane,gbc);
gbc.gridy = 5;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(field,gbc);
field.setBorder(BorderFactory.createTitledBorder("Enter text here:"));
gbc.gridy = 6;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(echo,gbc);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
//------------------------------------------------------------------------------
public void addListeners(){
echo.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
String message = field.getText();
field.setText("");
p.println(message);
try {
String reply = b.readLine();
if(reply!=null){
textArea.append(reply);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println();
}
});
}
//------------------------------------------------------------------------------
}
Can you please help me solve that problem?

Inside the server run () you need to have a while loop, which breaks only after your client says "close this connection". What is happening now is that your server is waiting for the data, client receives the data and exits (readline).
The exception is correct, if you think of it :).

Related

how to append message in JTextArea saying that a particular user is online or offline in client server

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();
}
}
}
}

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");

add jbutton at runtime

I am building an application on Socket programming in swing in which server listens for clients and if a client is connected I want
A button should be added for each client if connected on server screen
Add a listener on each button.For example add Send Message function for each client
I have created a thread in server which listens for client connections but I can not add jbutton at runtime.
Please reply.
Is that what you need ? :
import javax.swing.*;
import java.awt.event.*;
public class NewButtonOnRunTime {
static JPanel panel;
static JFrame frame;
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame = new JFrame("Add Buttons");
JButton button = new JButton("Simulate new Client");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
JButton jb = new JButton("A new Client");
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "This is an button action");
}
});
panel.add(jb);
frame.revalidate();
}
});
panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Assuming you already have some kind of isConnected bool,
if(isConnected){
JButton runTimeButton = new JButton();
runTimeButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//do all the things you need to do in here,
//alternatively, define this inner class somewhere else and pass in
// an instance of it
}
});
frame.add(runTimeButton);
}
Based on ServerSocket communication in java (i.e. TCP), if a client is connected to the server with a particular port say 5555, no other clients will not be able to connect to the server with the same port at the same time because the port is already in use. So, each client should be using different port if you want to get simultaneous communication with the clients.
Look at this sample code, it adds JButton at runtime when a new client is connected :
(run client code and server code in separate machine connected together)
Server code
package com.test.socket;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class ServerFrame extends JFrame {
private Map<Integer, SocketVO> serverSocketMap;
private int startingPort = 5555;
public ServerFrame() {
}
public ServerFrame(String title) {
super(title);
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setLayout(new FlowLayout());
initComponents();
serverSocketMap = new HashMap<Integer, SocketVO>();
keepStartServerSocket();
setVisible(true);
}
private JTextArea area = null;
private void initComponents() {
area = new JTextArea(20, 20);
add(area);
// addDynamicButton();
}
private void addDynamicButton(final int port) {
JButton button = new JButton("Client on " + port + " port");
add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
Socket socket = serverSocketMap.get(port).getSocket();
try {
String content = area.getText();
socket.getOutputStream().write(content.getBytes());
System.out.println("seding text area content to " + port);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
class SocketVO {
private ServerSocket serverSocket;
private Socket socket;
public ServerSocket getServerSocket() {
return serverSocket;
}
public void setServerSocket(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
}
private void keepStartServerSocket() {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
System.out.println("waiting for a client at port "
+ startingPort);
openServerSocket(startingPort);
startingPort++;
}
}
}).start();
}
private void openServerSocket(final int port) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
final Socket socket = serverSocket.accept();
SocketVO socketVO = new SocketVO();
socketVO.setServerSocket(serverSocket);
socketVO.setSocket(socket);
serverSocketMap.put(port, socketVO);
addDynamicButton(port);
checkForCosing(port, socket);
} catch (IOException e) {
e.printStackTrace();
}
}
private void checkForCosing(final int port, final Socket socket) {
new Thread(new Runnable() {
#Override
public void run() {
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] b = new byte[1024];
int read = 0;
try {
StringBuilder builder = new StringBuilder();
while ((read = inputStream.read(b)) != -1) {
builder.append(new String(b));
}
if (builder.toString().equals("close")) {
closeServerSocket(port);
System.out.println("server port " + port + " closed");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
/**
* the method to close corresponding sockets
*
* #param port
*/
private void closeServerSocket(int port) {
Socket socket = serverSocketMap.get(port).getSocket();
ServerSocket serverSocket = serverSocketMap.get(port).getServerSocket();
try {
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ServerFrame("Server Socket Frame");
}
}
Client code :
package com.test.socket;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private int startingPort = 5550;
private void bindToServer() {
while(true) {
try {
Socket socket = new Socket("127.0.0.1", startingPort);
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
byte[] b = new byte[1024];
int read = 0;
try {
StringBuilder builder = new StringBuilder();
while((read = inputStream.read(b)) != -1) {
builder.append(new String(b));
}
System.out.println("message from server : "+builder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
startingPort++;
}
if (startingPort == 5580) {
}
}
}
public static void main(String[] args) {
new Client().bindToServer();
}
}
As per your last comment:
I have tested the program with two clients. The server is connected to two clients successfully. But buttons are not added at runtime for each client.
You are able to connect with multiple client and you have added a button also but it's not visible on the server.
Calling validate() again on JFrame will solve your problem after adding new JButton.
public class Test extends JFrame {
private JButton field[];
public JButton[] getField() {
return field;
}
public void test(int n) {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
field = new JButton[n];
for (int i = 0; i < field.length; i++) {
field[i] = new JButton("" + i + "");
field[i].addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("clicked button");
}
});
panel.add(field[i]);
}
add(panel);
}
public static void main(String[] args) {
Test test = new Test();
test.setSize(300, 300);
test.setVisible(true);
test.setLocationRelativeTo(null);
test.test(5);
}
}

java swing frame not closing with X

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...

How do I get 2 computers to communicate to each other in java for an instant messenger?

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;

Categories