java swing frame not closing with X - java

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

Related

The method writeUTF() results in java.net.SocketException: Socket closed

I am new to design client and server in JAVA. Now I am trying to write a client presented by a GUI to communicate with my dictionary server. The client can do add, remove or query a word (three buttons). The code in the client is as the following:
public class DictionaryClient {
private static String ip;
private static int port;
private DataInputStream input = null;
private DataOutputStream output = null;
public static void main(String[] args) {
// IP and port
ip = args[0];
port = Integer.parseInt(args[1]);
DictionaryClient client = new DictionaryClient();
client.run(ip, port);
}
public void run(String ip, int port){
GUI g = new GUI();
try(Socket socket = new Socket(ip, port);) {
// Output and Input Stream
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
g.start();
JButton c2 = (JButton)g.getComponent(2);
JButton c3 = (JButton)g.getComponent(3);
JButton c4 = (JButton)g.getComponent(4);
c2.addActionListener(new ButtonAdd(g));
c3.addActionListener(new ButtonRemove(g));
c4.addActionListener(new ButtonQuery(g));
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
//Button: Add
public class ButtonAdd implements ActionListener{
GUI g = null;
//Constructor
public ButtonAdd(GUI g){
this.g = g;
}
public void actionPerformed(ActionEvent event) {
JTextField t1 = (JTextField)g.getComponent(1);
JLabel t6 = (JLabel)g.getComponent(6);
String word = t1.getText();
String definition = t6.getText();
JLabel t5 = (JLabel)g.getComponent(5);
try {
output.writeInt(1);
output.writeUTF(word);
output.writeUTF(definition);
output.flush();
String message = input.readUTF();
t5.setText("Status: ");
t6.setText(message);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
//Button: Remove
public class ButtonRemove implements ActionListener{
GUI g = null;
//Constructor
public ButtonRemove(GUI g){
this.g = g;
}
public void actionPerformed(ActionEvent event) {
JTextField t1 = (JTextField)g.getComponent(1);
String word = t1.getText();
JLabel t6 = (JLabel)g.getComponent(6);
JLabel t5 = (JLabel)g.getComponent(5);
try {
output.writeInt(2);
output.writeUTF(word);
output.flush();
t5.setText("Status: ");
String message = input.readUTF();
t6.setText(message);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
//Button: Query
public class ButtonQuery implements ActionListener{
GUI g = null;
//Constructor
public ButtonQuery(GUI g){
this.g = g;
}
public void actionPerformed(ActionEvent event) {
JTextField t1 = (JTextField)g.getComponent(1);
String word = t1.getText();
JLabel t5 = (JLabel)g.getComponent(5);
JLabel t6 = (JLabel)g.getComponent(6);
try {
output.writeInt(3);
output.writeUTF(word);
output.flush();
String message = input.readUTF();
t6.setText(message);
t5.setText("Definition: ");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
However, when every time I clicked on one of the three buttons, it always poped out the exception: java.net.SocketException: Socket closed on the line trying to send a message to the server, such as output.writeInt(1) or output.writeUTF(word) etc.
I totally have no idea what is going wrong. Why is the socket closed? I even do not have any close() in my code. Does anyone have any idea about it? Thank you so much!
I think you might want to have a look at your server side code. The socket could well be getting closed on that side after a connect.

Java Swing : JTabbed for putting new component in tab

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

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

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

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

Categories