Swing VS. Sockets!

Hi Swing Programmers!
I need an urgent help please. I'm doing a Peer to Peer program, but i have a problem with the Swing thread I guess. When I run the two windows (Cleint & Server), then I click the Connect button at the Client window, it connects and everything goes alright, and I can see my connection status in the Server window, but not at the Client window. Just when I click connect, the Client window freez & hangs. The Server side works alright, he can even type messages, but they are not sent to the Client. But the wiered thing, just when the Server hits the Disconnect button, the Client window goes back to the normal state, and prints all the Server messages!
Can anyone help me with that? Find the 2 files below, note that you have to pass the local & remote port when running the program. As:
java ClientSide port1 port2
java ServerSide port2 port1
Thanks.
// CLIENT
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClientSide extends JFrame implements ActionListener
     private JLabel title;
     private JTextArea MessageArea;
     private JScrollPane Scroll_MsgArea;
     private JTextArea Input;
     private JScrollPane Scroll_Input;
     private JButton Connect;
     private JButton Disconnect;
     private JButton Send;
     private String message;
     private static String temp_local;
     private static String temp_remote;
     private static int local;
     private static int remote;
     private ServerSocket server;
     private Socket connection;
     private ObjectInputStream input;
     private ObjectOutputStream output;
     public ClientSide ()     
          super("Peer to Peer Socket Program");
          guiLayout customLayout = new guiLayout();
          Container c= getContentPane();
          c.setLayout(customLayout);
          title= new JLabel("Welcome!");
          c.add(title);
          MessageArea= new JTextArea();
          MessageArea.setEnabled(false);
          c.add(MessageArea);
          Scroll_MsgArea= new JScrollPane();
          //c.add(Scroll_MsgArea);
          //c.add(new JScrollPane(MessageArea));
          Input= new JTextArea();
          c.add(Input);
          Input.setEnabled(false);
          Scroll_Input= new JScrollPane();
          //c.add(Scroll_Input);
          Send= new JButton("Send");
          c.add(Send);
          Send.setEnabled(false);
          Connect= new JButton("Connect");
          c.add(Connect);
          Disconnect= new JButton("Disconnect");
          c.add(Disconnect);
          Disconnect.setEnabled(false);
          Connect.addActionListener(this);
          Send.addActionListener(this);
          Disconnect.addActionListener(this);
MessageArea.setText("\nClick Connect to start a communication channel");
     public void Client(int remote)
     try
     while(true)
          MessageArea.append("\nAttempting to connect...");
     connection= new Socket("139.182.139.102", remote);
MessageArea.append("\nConnected to: " + connection.getInetAddress().getHostAddress());
Input.setEnabled(true);
     //IO Streams
     output= new ObjectOutputStream(connection.getOutputStream());
               output.flush();
     input= new ObjectInputStream(connection.getInputStream());
          MessageArea.append("\nI/O Streams Received");
     Disconnect.setEnabled(true);
     //Process Connection
     Input.setEnabled(true);
               do {
                    try {
                         message= (String) input.readObject();
                         MessageArea.append("\n>>" + message);
                         MessageArea.setCaretPosition(MessageArea.getText().length());
     catch(ClassNotFoundException cnf){MessageArea.append("\nUnknown Input");}
while( !message.equals("\nUnknown Input"));
     catch(IOException io)
               MessageArea.append("\nConnection Terminated");
               Disconnect.setEnabled(false);
               Send.setEnabled(false);
               Connect.setEnabled(false);
     public void actionPerformed(ActionEvent e)
          if(e.getActionCommand() == "Connect")
                    Connect.setEnabled(false);
                    Client(remote);
          if(e.getActionCommand()== "Send")
               Send();
          if(e.getActionCommand() == "Disconnect")
               Disconnect();
     public void Send()
          try {
               output.writeObject("\n>> " + Input.getText());
               MessageArea.append("\n>> " + Input.getText());
               output.flush();
               Input.setText("");
          catch(IOException io){MessageArea.append("\nError Writing Data");}     
public void Disconnect()
          try{
               MessageArea.append("\n +-+-+ TERMINATED +-+-+");
               Input.setEnabled(false);
               output.close();
               input.close();
               connection.close();
               Disconnect.setEnabled(false);
               Send.setEnabled(false);
          catch(IOException io){MessageArea.append("\nError Writing Data");}     
     public static void main(String args[])
          ClientSide win= new ClientSide ();
          win.pack();
          win.show();
          temp_local= args[0];
          temp_remote= args[1];
          local= Integer.parseInt(temp_local);
          remote= Integer.parseInt(temp_remote);
          win.setDefaultCloseOperation(EXIT_ON_CLOSE);
//GUI stuff
class guiLayout implements LayoutManager {
public guiLayout() {
public void addLayoutComponent(String name, Component comp) {}
public void removeLayoutComponent(Component comp) {}
public Dimension preferredLayoutSize(Container parent) {
Dimension dim = new Dimension(0, 0);
Insets insets = parent.getInsets();
dim.width = 342 + insets.left + insets.right;
dim.height = 420 + insets.top + insets.bottom;
return dim;
public Dimension minimumLayoutSize(Container parent) {
Dimension dim = new Dimension(0, 0);
return dim;
public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
Component c;
c = parent.getComponent(0);
if (c.isVisible()) {c.setBounds(insets.left+80,insets.top+16,176,24);}
c = parent.getComponent(1);
if (c.isVisible()) {c.setBounds(insets.left+40,insets.top+48,264,200);}
c = parent.getComponent(2);
if (c.isVisible()) {c.setBounds(insets.left+40,insets.top+256,192,48);}
c = parent.getComponent(3);
if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+264,72,32);}
c = parent.getComponent(4);
if (c.isVisible()) {c.setBounds(insets.left+40,insets.top+336,85,24);}
c = parent.getComponent(5);
if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+336,85,24);}
//SERVER
/* A P2P program, developed by ELHARITH ELRUFAIE, for the CSCI 660 lab.
SERVER SIDE */
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// SERVER SIDE
public class ServerSide extends JFrame implements ActionListener
     private JLabel title;
     private JTextArea MessageArea;
     private JScrollPane Scroll_MsgArea;
     private JTextArea Input;
     private JScrollPane Scroll_Input;
     private JButton Disconnect;
     private JButton Send;
     private String message;
     private static String temp_local;
     private static String temp_remote;
     private static int local;
     private static int remote;
     private ServerSocket server;
     private Socket connection;
     private ObjectInputStream input;
     private ObjectOutputStream output;
     public ServerSide()     
          super("Peer to Peer Socket Program");
          guiLayout customLayout = new guiLayout();
          Container c= getContentPane();
          c.setLayout(customLayout);
          title= new JLabel("Welcome!");
          c.add(title);
          MessageArea= new JTextArea();
          MessageArea.setEnabled(false);
          c.add(MessageArea);
          Scroll_MsgArea= new JScrollPane();
          //c.add(Scroll_MsgArea);
          //c.add(new JScrollPane(MessageArea));
          Input= new JTextArea();
          c.add(Input);
          Input.setEnabled(false);
          Scroll_Input= new JScrollPane();
          //c.add(Scroll_Input);
          Send= new JButton("Send");
          c.add(Send);
          Send.setEnabled(false);
          Disconnect= new JButton("Disconnect");
          c.add(Disconnect);
          Disconnect.setEnabled(false);
          Send.addActionListener(this);
          Disconnect.addActionListener(this);
     public void Server(int local)
     try{
          server= new ServerSocket(local);
while(true)
          //Receiving the Connection
          MessageArea.setText("\nWaiting for Connection...");
          connection= server.accept();
          MessageArea.append("\nReceiving connection from " + connection.getInetAddress().getHostAddress());
          //IO Streams
          output= new ObjectOutputStream(connection.getOutputStream());
          output.flush();
          input= new ObjectInputStream(connection.getInputStream());
          MessageArea.append("\nI/O Streams Received\n");
          //Process the Connection()
          Input.setEnabled(true);
          String message= "==> Connected Successfully...";     
          output.writeObject(message);
          output.flush();
          MessageArea.append(message);
          Send.setEnabled(true);
          Disconnect.setEnabled(true);
          do {
          try {
                    message= (String) input.readObject();
                    MessageArea.append("\n" + message);
          catch(ClassNotFoundException cnf)
                    {MessageArea.append("\nUnknown Input");}
               output.writeObject(Input.getText());
               output.flush();     
while( !message.equals("\nUSER>> TERMINATED"));
     catch(IOException iof) {MessageArea.append("\nDisconnected Sucessfully");}     
     public void actionPerformed(ActionEvent e)
          if(e.getActionCommand()== "Send")
               Send();
          if(e.getActionCommand() == "Disconnect")
               Disconnect();
     public void Send()
          try {
               output.writeObject("\n>> " + Input.getText());
               MessageArea.append("\n>> " + Input.getText());
               output.flush();
               Input.setText("");
          catch(IOException io){MessageArea.append("\nError Writing Data");}     
     public void Disconnect()
          try{
               MessageArea.append("\n +-+-+ TERMINATED +-+-+");
               Input.setEnabled(false);
               output.close();
               input.close();
               connection.close();
               Disconnect.setEnabled(false);
               Send.setEnabled(false);
          catch(IOException io){MessageArea.append("\nError Writing Data");}     
     public static void main(String args[])
          ServerSide win= new ServerSide();
          win.pack();
          win.show();
          temp_local= args[0];
          temp_remote= args[1];
          local= Integer.parseInt(temp_local);
          remote= Integer.parseInt(temp_remote);
          win.Server(local);
          win.setDefaultCloseOperation(EXIT_ON_CLOSE);
//GUI stuff
class guiLayout implements LayoutManager {
public guiLayout() {
public void addLayoutComponent(String name, Component comp) {}
public void removeLayoutComponent(Component comp) {}
public Dimension preferredLayoutSize(Container parent) {
Dimension dim = new Dimension(0, 0);
Insets insets = parent.getInsets();
dim.width = 342 + insets.left + insets.right;
dim.height = 420 + insets.top + insets.bottom;
return dim;
public Dimension minimumLayoutSize(Container parent) {
Dimension dim = new Dimension(0, 0);
return dim;
public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
Component c;
c = parent.getComponent(0);
if (c.isVisible()) {c.setBounds(insets.left+80,insets.top+16,176,24);}
c = parent.getComponent(1);
if (c.isVisible()) {c.setBounds(insets.left+40,insets.top+48,264,200);}
c = parent.getComponent(2);
if (c.isVisible()) {c.setBounds(insets.left+40,insets.top+256,192,48);}
c = parent.getComponent(3);
if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+264,72,32);}
c = parent.getComponent(4);
if (c.isVisible()) {c.setBounds(insets.left+232,insets.top+336,85,24);}

After running your programs, I got a clearer idea of what was wrong. AFAIK, the following are wrong with your programs:
1. Your calling of "win.Server(local);" in ServerSide.java after some Swing components in your program have been realised is not thread safe. Put the call to that method in the event-dispatching thread of the program.
Also in your programs, you shouldn't have called the "setDefaultCloseOperation" method after the "pack" mthod. This is also not thread safe.
2. The do-while statement in the "Client" method of ClientSide.java causes your program to get stuck in its event-dispatching thread after it (your program) calls the "Client" method from one of the event handlers. That's why ClientSide is even unable to repaint itself when necessary after getting stuck. Perhaps you should move any method that may stall the event-dispatching thread to a seperate thread.

Similar Messages

  • Java Swing and Socket Programming

    I am making a Messenger like yahoo Messenger using Swing and Socket Programming ,Multithreading .
    Is this techology feasible or i should try something else.
    I want to display my messenger icon on task bar as it comes when i install and run Yahoo Messenger.
    Which class i should use.

    I don't really have an answer to what you are asking. But I am developing the same kind of application. I am using RMI for client-server and server-server (i have distributed servers) communication and TCP/IP for client-client. So may be we might be able to help each other out. My email id is [email protected]
    Are you opening a new socket for every conversation? I was wondering how to multithread a socket to reuse it for different connections, if it is possible at all.
    --Poonam.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Help needed with swings for socket Programming

    Im working on a Project for my MScIT on Distributed Computing...which involves socket programming(UDP)....im working on some algorithms like Token Ring, Message Passing interface, Byzantine, Clock Syncronisation...i hav almost finished working on these algorithms...but now i wanna give a good look to my programs..using swings but im very new to swings...so can anyone help me with some examples involving swings with socket programming...any reference...any help would be appreciated...please help im running out of time..
    thanking u in advance
    anDy

    hi im Anand(AnDY),
    i hav lost my AnDY account..plz reply to this topic keeping me in mind :p

  • Client-Server programming with Sockets

    How to read user input from GUI in client socket and send the data to server socket? Can someone give example of the coding?
    Thank you.

    Take a look at reply 28 of Program hanging on a Thread. That post is a swing based socket client. If you are using Swing you must ensure that all swing activity occurs on the AWT Event Dispatch Thread. That's the reason for the use of invokeLater.
    Reply 21 on the same thread is a multithreaded command line server.

  • Telnet application.....

    hi........
    Iam developing an telnet application with authentication..
    For this i have written a server & client classes.. When i execute the client program, it will ask for ip address of the machine to telnet..
    I have designed the server program in such a way that when it is executed, it will ask for the port no. to listen to. (eg. any no. 1234)
    when i give 1234 in the client part, it will connect. & the server will increment the value of no.of users connected as 1..
    I dont in this way..... When the server is executed, it has to listen for the port no. 23 which is the default port for Telnet..... And if the client gives the ip address to connect, it will connect to the server.....
    I dun know how to make it (server) to make it listen for the port automatically..
    How can I do this????

    You mean the server should listen to port 23 automatically?
    It seems to be doing that... so I dont know what you mean by automatically?hiii.....
    What i mean is, at present when i execute the server part, i have to manually fill the port no. & click the listen to port button to make it to listen the port for any connections coming from clients... I developed it in swings & used sockets for connections,....
    Basically it was the ftp project done in swings used for downloading files..... did u get it???
    Now i have to develop this telnet application..... For this, when i execute server, it should automatically listen for the port 23 for incoming connections....
    did u get it????
    How to make it....
    P.S: In the previous FTP application, I give any no. (2345) or any such nos less than 65550 as the port no. for listening for connections...
    In this i have to make the server to look for port 23 (telnet port) as default..
    thanxs....
    saravanan.

  • Java Swing App hangs on socket loop

    H}ello everyone i've run into a bit of a snag with my application, its a simple chat bot right now but will evolve into a chat client soon. I can't do that however since my app hangs when i look through the readLine() function to receive data and i dont know how to fix this error. The code is below.
    The doSocket() function is where the while loop is if anyone can help me with this i'd be very greatful.
    * GuiFrame.java
    * Created on August 13, 2008, 9:36 PM
    import java.net.*;
    import java.io.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author  brian
    public class GuiFrame extends javax.swing.JFrame {
        /** Creates new form GuiFrame */
        public GuiFrame() {
            initComponents();
        Socket client_sock = null;
        PrintWriter out = null;
        BufferedReader in = null;
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            convertButton = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Test Bot");
            convertButton.setText("Connect");
            convertButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    convertButtonActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(41, 41, 41)
                    .addComponent(convertButton)
                    .addContainerGap(42, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addComponent(convertButton)
                    .addContainerGap(26, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
    private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        if (convertButton.getText()=="Connect") {
                    String old;
                    try {
                        client_sock = new Socket("www.spinchat.com", 3001);
                        out = new PrintWriter(client_sock.getOutputStream(), true);
                        in = new BufferedReader(new InputStreamReader(client_sock.getInputStream()));
                    } catch (UnknownHostException e) {
                    } catch (IOException e) {
                try {
                    doSocket();
                } catch (IOException ex) {
                    Logger.getLogger(GuiFrame.class.getName()).log(Level.SEVERE, null, ex);
        } else if (convertButton.getText()=="Disconnect") {
            out.println("e");
            out.close();
            try {
                client_sock.close();
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(GuiFrame.class.getName()).log(Level.SEVERE, null, ex);
    private void doSocket() throws IOException {
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String userInput;
        String old;
            while ((userInput = stdIn.readLine()) != null) {
                old = userInput;
                if (userInput != old) {
                    String proto = userInput.substring(0, 0);
                    if (proto == ":") {
                        out.println("{2");
                        out.println("BI'm a bot.");
                        out.println("aNICKHERE");
                        out.println("bPASSHERE");
                    } else if (proto == "a") {
                        convertButton.setText("Disconnect");
                        out.println("JoinCHannel");
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new GuiFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JButton convertButton;
        // End of variables declaration                  
    }Edited by: briansykes on Aug 13, 2008 9:55 PM
    Edited by: briansykes on Aug 13, 2008 9:56 PM

    >
    ..i've run into a bit of a snag with my application, its a simple chat bot right now but will evolve into a chat client soon. >Is this intended as a GUId app? If so, I would stick to using a GUI for input, rather than reading from the command line (which when I run it, is the DOS window that jumps up in the BG - quite counterintuitive). On the other hand, if it is intended as a non-GUId or headless app., it might be better to avoid any use of JComponents at all.
    My edits stick to using a GUI.
    Other notes:
    - String comparison should be done as
    s1.equals(s2)..rather than..
    s1 == s2- Never [swallow exceptions|http://pscode.org/javafaq.html#stacktrace] in code that does not work.
    - Some basic debugging skills are well called for here, to find where the program is getting stuck. When in doubt, print out!
    - What made you think that
    a) a test of equality on a member against which you had just set the value to the comparator, would logically lead to 'false'?
    old = userInput;
    if (userInput != old) ..b) A substring from indices '0 thru 0' would provide 1 character?
    String proto = userInput.substring(0, 0);
    if (proto == ":") ..
    >
    ..if anyone can help me with this i'd be very greatful.>Gratitude is often best expressed through the offering of [Duke Stars|http://wikis.sun.com/display/SunForums/Duke+Stars+Program+Overview].
    * GuiFrame.java
    * Created on August 13, 2008, 9:36 PM
    import java.net.*;
    import java.io.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    * @author  brian
    public class GuiFrame extends JFrame {
        /** Creates new form GuiFrame */
        public GuiFrame() {
            initComponents();
        Socket client_sock = null;
        PrintWriter out = null;
        BufferedReader in = null;
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            convertButton = new JButton();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Test Bot");
            convertButton.setText("Connect");
            convertButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    convertButtonActionPerformed(evt);
            GroupLayout layout = new GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(41, 41, 41)
                    .addComponent(convertButton)
                    .addContainerGap(42, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addComponent(convertButton)
                    .addContainerGap(26, Short.MAX_VALUE))
            pack();
            setLocationByPlatform(true);
        }// </editor-fold>
    private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
        if (convertButton.getText()=="Connect") {
                    String old;
                    try {
                        System.out.println( "Connect start.." );
                        client_sock = new Socket("www.spinchat.com", 3001);
                        out = new PrintWriter(client_sock.getOutputStream(), true);
                        in = new BufferedReader(new InputStreamReader(client_sock.getInputStream()));
                        System.out.println( "Connect end.." );
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                try {
                    doSocket();
                } catch (IOException ex) {
                    Logger.getLogger(GuiFrame.class.getName()).log(Level.SEVERE, null, ex);
        } else if (convertButton.getText()=="Disconnect") {
            out.println("e");
            out.close();
            try {
                client_sock.close();
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(GuiFrame.class.getName()).log(Level.SEVERE, null, ex);
        private void doSocket() throws IOException {
            System.out.println( "doSocket start.." );
            String userInput;
            String old;
            userInput = JOptionPane.showInputDialog(this, "Send..");
            while(userInput!=null && userInput.trim().length()>0) {
                System.out.println( "doSocket loop 1.." );
                String proto = userInput.substring(0, 1);
                System.out.println("proto: '" + proto + "'");
                if (proto.equals(":")) {
                    System.out.println("Sending data..");
                    out.println("{2");
                    out.println("BI'm a bot.");
                    out.println("aNICKHERE");
                    out.println("bPASSHERE");
                } else if (proto.equals("a")) {
                    convertButton.setText("Disconnect");
                    out.println("JoinCHannel");
                userInput = JOptionPane.showInputDialog(this, "Send..");
            System.out.println( "doSocket end.." );
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new GuiFrame().setVisible(true);
        // Variables declaration - do not modify
        private JButton convertButton;
        // End of variables declaration
    }

  • Using Swing how can we create socket and send data thru TCP/IP on the socke

    Hi All,
    Can anyone tell the link or answer to me about the Socket programming using Swing and data get & post onto the socket.
    Thanx & Regard
    Ashu

    swing is nothing to do with socket programing, you need to code using core java and API of net
    so please go through this link [http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html]

  • How canI call the socket by swing? I have asocket code already

    Socket sock=new Socket("localhost",Integer.parseInt(args[1]));
                DataInputStream input = new DataInputStream(sock.getInputStream());
                DataOutputStream output=new DataOutputStream(sock.getOutputStream());
                PrintStream command = new PrintStream(sock.getOutputStream());
                BufferedReader buffer= new BufferedReader(new InputStreamReader(sock.getInputStream()));
                String userInput="GO 100";
                int size=userInput.length();
                 byte[] asciiBytes = userInput.getBytes("US-ASCII");
                 int sum=0;
                 for(int i=0;i<size;i++){
                     int j=asciiBytes;
    sum=sum+j;
    command.print(userInput+" "+sum);
    System.out.print(buffer.readLine());
    that onefor socket but I have GUI button to submit the ip. How can I call socket because on GUI we don't have throw IOException here is the main I just want after submit. My program take args[1] into the ip and call server. How can I do that?
        public static void main(String args[]) throws IOException{
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new client_gui().setVisible(true);

    Swing has nothing to do with a Socket connection.
    Read the tutorial on [url http://java.sun.com/docs/books/tutorial/]Custom Networking for examples of using a Socket.

  • Socket connect slow in JDK 1.5?

    We recently began testing our Java Swing application with JDK 1.5, and we noticed that socket.connect()
    calls are taking several seconds to return, when before in 1.4 the calls returned immediately.
    Here is some sample code:
    Socket sock = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(inAddress, portNum);
    sock.connect(sockAddr, 2000);
    What could be wrong? I've debugged the code and verified inAddress is an IP address,
    not a hostname.
    -Eric

    Here is the list of enhancements in JDK1.5.
    http://java.sun.com/j2se/1.5.0/docs/guide/net/enhancements-1.5.0.html
    I wonder if any of them are having some effect in the slow connection.
    There are some network properties that you can tweak with. Did you try them?
    Here is the list
    http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html

  • Chat room using multicast socket

    hi-
    i have a chat room based on multicast socket with a SWING GUI interface. i want group members to be able to establish a shared secret(bases on extended n-party diffie-hellman algorithm) to encrypt all messages exchanged . Re-keying happens upon member join and leave. In order to do key agreement i need to identify the number of subscribers in the multicast chat room all time. i am having trouble setting up a centralized counter to keep track of distributed users 'cause each time a user joins the chat he or she invokes a different copy of the chat program(command line usage: java chatroom <user name>). please help me setting up a counter to count the subscriber and identify joins and leaves.... my main questin is where within the program to set up a counter variable like this to keep track of distributed users? please help...thanks!

    thanks for your reply... ummm yeah securing a chat room based on multicast poses many problems mainly because of the lack of a chat server. i really haven't gotten any of them sorted out. well the only reason to use encryption is to provide perfect forward secrecy and backward secrecy, meaning a user who just joined the chat room can't decipher any previous session of conversation prior to his join and a user who just left the chat room can't use the group session key he had to decrypt any future conversation. Access control and authorization is ignored. User can join the chat room without permission of the existing members.
    yes a flat hierarchy is assumed(all group members are treated equally....no fixed member is given privilege to generate and distribute keys). However, for the key agreement protocol to take place the last joined member is chosen as a group leader and is responsible of re-keying his share in the previous group session key. The newly joined member adds his share and everybody computes the new group session key based on Diffie-Hellman. This group leader role floats...
    you are right... without being able to detect joins/leaves and the correct order of those joins and leaves, none of these can be realized.
    Can i chain a separate server just to keep track of membership changes?

  • I suppose it is the problem with socket connection,Please help

    Hi,
    I'm trying to build a chat server in Java on Linux OS.I've created basically 2 classes in the client program.The first one shows the login window.When we enter the Login ID & password & click on the ok button,the data is sent to the server for verification.If the login is true,the second class is invoked,which displays the messenger window.This class again access the server
    for collecting the IDs of the online persons.But this statement which reads from the server causes an exception in the program.If we invoke the second class independently(ie not from 1st class) then there is no problem & the required data is read from the server.Can anyone please help me in getting this program right.I'm working on a p4 machine with JDK1.4.
    The Exceptions caused are given below
    java.net.SocketException: Connection reset by peer: Connection reset by peer
    at java.net.SocketInputStream.SocketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:119)
         at java.io.InputStreamReader$CharsetFiller.readBytes(InputStreanReader.java :339)
         at java.io.InputStreamReader$CharsetFiller.fill(InputStreamReader.java:374)
         at java.io.InputStreamReader.read(InputStreamReader.java:511)
         at java.io.BufferedReader.fill(BufferedReader.java:139)
         at java.io.BufferedReader.readLine(BufferedReader.java:299)
         at java.io.BufferedReader.readLine(BufferedReader.java:362)
         at Login.LoginData(Login.java:330)
         at Login.test(Login.java:155)
         at Login$Buttonhandler.actionPerformed(Login.java:138)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1722)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:17775)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:4141)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:253)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:261)
         at java.awt.Component.processMouseEvent(Component.java:4906)
         at java.awt.Component.processEvent(component.java:4732)
         at java.awt.Container.processEvent(Container.java:1337)
         at java.awt.component.dispatchEventImpl(Component.java:3476)
         at java.awt.Container.dispatchEventImpl(Container.java:1399)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3302)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3014)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2967)
         at java.awt.Container.dispatchEventImpl(Container.java:1373)
         at java.awt.window.dispatchEventImpl(Window.java:1459)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:439)
         at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
         My program looks somewhat like this :
    1st class definition:
    public class Login extends Jframe// Login is the name of the first class;
    Socket connection;
    DataOutputStream outStream;
    BufferedReader inStream;
    Frame is set up here
    public class Buttonhandler implements ActionListener
    public void actionPerformed(ActionEvent e) {
    String comm = e.getActionCommand();
    if(comm.equals("ok")) {
    check=LoginCheck(ID,paswd);
    test();
    public void test() //checks whether the login is true
    if(check)
    new Messenger(ID);// the second class is invoked
    public boolean LoginCheck(String user,String passwd)
    //Enter the Server's IP & port below
    String destination="localhost";
    int port=1234;
    try
    connection=new Socket(destination,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStream = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    outStream=new DataOutputStream(connection.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    System.out.println("connected to "+destination+" at port "+port+".");
    BufferedReader keyboardInput=new BufferedReader(new InputStreamReader(System.in));
    String receive=new String();
    try{
    receive=inStream.readLine();
    }catch(IOException ex){ error("Error reading from server");}
    if(receive.equals("Logintrue"))
    check=true;
    else
    check=false;
    try{
    inStream.close();
    outStream.close();
    connection.close();
    }catch (IOException ex){
    error("IO error closing socket");
    return(check);
    // second class is defined below
    public class Messenger
    Socket connect;
    DataOutputStream outStr;
    BufferedReader inStr;
    public static void main(String args[])
    { Messenger mes = new Messenger(args[0]);}
    Messenger(String strg)
    CreateWindow();
    setupEvents();
    LoginData(strg);
    fram.show();
    void setupEvents()
    fram.addWindowListener(new WindowHandler());
    login.addActionListener(new MenuItemHandler());
    quit.addActionListener(new MenuItemHandler());
    button.addActionListener(new Buttonhandle());
    public void LoginData(String name)
    //Enter the Server's IP & port below
    String dest="localhost";
    int port=1234;
    int r=0;
    String str[]=new String[40];
    try
    connect=new Socket(dest,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStr = new BufferedReader(new InputStreamReader(connect.getInputStream()));
    outStr=new DataOutputStream(connect.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    String codeln=new String("\n");
    try{
    outStr.flush();
    outStr.writeBytes("!@*&!@#$%^");//code for sending logged in users
    outStr.writeBytes(codeln);
    outStr.write(13);
    outStr.flush();
    String check="qkpltx";
    String receive=new String();
    try{
    while((receive=inStr.readLine())!=null) //the statement that causes the exception
    if(receive.equals(check))
    break;
    else
         str[r]=receive;
         r++;
    }catch(IOException ex){ex.printStackTrace();error("Error reading from socket");}
    catch(NullPointerException ex){ex.printStackTrace();}
    } catch (IOException ex){ex.printStackTrace();
    error("Error reading from keyboard or socket ");
    try{
    inStr.close();
    outStr.close();
    connect.close();
    }catch (IOException ex){
    error("IO error closing socket");
    for(int l=0,k=1;l<r;l=l+2,k++)
    if(!(str[l].equals(name)))
    stud[k]=" "+str[l];
    else
    k--;
    public class Buttonhandle implements ActionListener
    public void actionPerformed(ActionEvent e) {
    //chat with the selected user;
    public class MenuItemHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    String cmd=e.getActionCommand();
    if(cmd.equals("Disconnect"))
    //Disconnect from the server
    else if(cmd.equals("Change User"))
         //Disconnect from the server & call the login window
    else if(cmd.equals("View Connection Details"))
    //show connection details;
    public class WindowHandler extends WindowAdapter
    public void windowClosing(WindowEvent e){
    //Disconnect from server & then exit;
    System.exit(0);}
    I�ll be very thankful if anyone corrects the mistake for me.Please help.

    You're connecting to the server twice. After you've successfully logged in, pass the Socket to the Messenger class.
    public class Messenger {
        Socket connect;
        public static void main(String args[]) {
            Messenger mes = new Messenger(args[0]);
        Messenger(Socket s, String strg) {
            this.connect = s;
            CreateWindow();
            setupEvents();
            LoginData(strg);
            fram.show();
    }

  • Problem with socket object writing

    hi,
    I made this little programm , with a class point , a server and a client.
    I try to send via the socket several point object.
    If send differents objects ( with several new point(... )) it works fine , but if i send the same object changing only the properties it doesn't work. Changing are not applicate.
    Here is the code.
    // POINT
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
        private int x_;
        private int y_;
        private Color c_;
        public point(int x, int y, Color c) {
           x_=x;
           y_=y;
           c_=c;
        public int get_x() { return x_ ; }
        public int get_y() { return y_ ; }
        public void set_x(int x) { x_=x ; }
        public void set_y(int y) { y_=y ; }
        public Color get_color() { return c_ ; }
    // SERVER
    import java.io.*;
    import java.net.*;
    public class s {
        public s()
            try
                ServerSocket server = new java.net.ServerSocket(80);
                java.net.Socket client  = server.accept();
                ObjectInputStream Istream_ = new ObjectInputStream(client.getInputStream());
                ObjectOutputStream Ostream_ = new ObjectOutputStream(client.getOutputStream());
                for(int i=0;i<4;i++)
                    point p_read = (point)Istream_.readObject();
                    System.out.print("x="+p_read.get_x());
                    System.out.println(" y="+p_read.get_y());
             catch (Exception exception) { exception.printStackTrace(); }
        public static void main(String args[])
         s s_ = new s();
    // CLIENT
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    public class c {
        public c()
            try
                ipJDialog ipjd = new ipJDialog();
                String ip = ipjd.getvalue();
                Socket socket  = new Socket(ip,80);
                System.out.println("connection avec serveur reussi");
                ObjectOutputStream Ostream_ = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream Istream_ = new ObjectInputStream(socket.getInputStream());
                point p1 = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p1);
                point p2 = new point(22,30, new Color(255,0,0));
                Ostream_.writeObject(p2);
                point p3 = new point(8,7, new Color(255,0,0));
                Ostream_.writeObject(p3);
                point p4 = new point(2,1, new Color(255,0,0));
                Ostream_.writeObject(p4);
             catch (Exception exception) {exception.printStackTrace();}
        public static void main(String args[])
         c c_ = new c();
    // DIALOG TO GET IP FROM INPUTBOX
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ipJDialog extends JDialog implements ActionListener {
        private String ip_;
        private JTextArea jta_;
        private JTextField jtf_;
        private JButton jb1_;
        public ipJDialog()
            this.getContentPane().setLayout(null);
            this.setTitle("Entrez l'IP du serveur");
            this.setSize(220,100);
            this.setModal(true);
            ip_= "localhost";
            jta_ = new JTextArea("IP du serveur :");
            jta_.setBounds(10,5, 90,20);
            jta_.setOpaque(false);
            jta_.setEditable(false);
            getContentPane().add(jta_);
            jtf_ = new JTextField();
            jtf_.setBounds(110,5, 90,20);
            jtf_.requestFocus();
            getContentPane().add(jtf_);
            jb1_ = new JButton("OK");
            jb1_.setBounds(10,30, 90,30);
            jb1_.addActionListener(this);
            getContentPane().add(jb1_);
            this.setVisible(true);
        public String getvalue() { return ip_ ; }
        public void actionPerformed(ActionEvent evt)
            String ChoixOption = evt.getActionCommand();
         if(ChoixOption.equals("OK"))
                ip_=jtf_.getText();
                this.setVisible(false);
    if I replace in client :
             point p1 = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p1);
                point p2 = new point(22,30, new Color(255,0,0));
                Ostream_.writeObject(p2);
                point p3 = new point(8,7, new Color(255,0,0));
                Ostream_.writeObject(p3);
                point p4 = new point(2,1, new Color(255,0,0));
                Ostream_.writeObject(p4);
    by :
             point p = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p);
                p.set_x(20);
                p.set_x(22);
                Ostream_.writeObject(p);
                p.set_x(55);
                p.set_x(32);
                Ostream_.writeObject(p);
                p.set_x(14);
                p.set_x(88);
                Ostream_.writeObject(p);
    I doesn't work , i receive a point with 50,50 ( the first one ) four times ...If you can explain me me why and what can I do ...
    Thx.

    For ObjectOutputStream, multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written. State of a object will be recorded so that the ObjectOutputStream doesn't writes the same object to the outputstream when the object was refered by multiple references. So, when you tried to write the same object agains into the ObjectOutputStream, the ObjectOutputStream doesn't write the object, but passed the as a reference to the outputstream... In this case, on the other side, the ObjectInputStream will receive this reference and it will return the reference of this object (which is previous created when this object was passed over on the 1st time). This caused the ObjectInputStream will return a "unchanged" object even your object have changed before you write it agains to the ObjectOutputStream.
    My explaination maybe not that good... hope you can understand... :)

  • Problem with socket and object writing

    Hi,
    I programm this client/server app, the client has a point (graphic ) , the server has a point and when the mouse is moving it moves the point and the new position is send via the socket.
    The probleme is that i don't receive the good thing.
    When i display the coord of the point before sending it's good , but when receiving from the socket the coords are always the same ...
    i don't understand .
    Well , try and tell me ...
    Thx.

    oups, the program can be usefull ...
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class server_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    server s;
    public server_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p2=new point(50,50,new Color(0,0,255));
    p1=new point(200,200,new Color(255,0,0));
    s = new server(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    s.write_point(p1);
    repaint();
    public static void main(String args[])
         server_JFrame sjf = new server_JFrame();
    sjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         sjf.setTitle("server");
    sjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class server {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public server(point p,Container c)
    p_=p;
    c_=c;
    try
    ServerSocket server = new java.net.ServerSocket(80);
    System.out.println("attente d'un client");
    java.net.Socket client = server.accept();
    System.out.println("client accept�");
    Istream_ = new ObjectInputStream(client.getInputStream());
    Ostream_ = new ObjectOutputStream(client.getOutputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) { exception.printStackTrace(); }
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class client_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    client c;
    public client_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p1=new point(50,50,new Color(0,0,255));
    p2=new point(200,200,new Color(255,0,0));
    c = new client(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    c.write_point(p1);
    repaint();
    public static void main(String args[])
         client_JFrame cjf = new client_JFrame();
    cjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         cjf.setTitle("client");
    cjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
    private int x_;
    private int y_;
    private Color c_;
    public point(int x, int y, Color c) {
    x_=x;
    y_=y;
    c_=c;
    public int get_x() { return x_ ; }
    public int get_y() { return y_ ; }
    public void set_x(int x) { x_=x ; }
    public void set_y(int y) { y_=y ; }
    public Color get_color() { return c_ ; }
    }

  • Problem in using swing application

    hi friends, iam developed a swing gui in that iam going to give server port number and number of clients handled by the server.Then i press submit button.The action am writed for the submit button is my server program reads the configuration details from the file and then server socket establishes and waits in the accept socket.At this stage,my swing gui gets freezed.... but i dont need that.... coz in that iam using the other button which is used to stop the server program.... can anyone tell me whats the problem and whats the solution?

    You need to use a separate Thread for your Socket connection so you don't block the GUI:
    http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

  • A beginner in socket programming

    Ok I am been stuck on this program for the whole day trying to figure out why I cannot connect to my server computer using sockets and threads.
    I am trying to implement a instant messenger program where each user acts has both client/server. Each client creates a listening socket and all use a common port number, (in this case port 4444).
    If client 1 wants to interact with client 2, client 1 query�s my MySQL database for their status. Now if their status is online, retrieve their current ip address. So far so good. My program does not with no problem.
    Now comes the painful part. Now that client 1 knows client 2 is online and has his/hers ip, the next step is to connect to client 2�s listening socket using their ip and the port number 4444. Now after connecting to that socket, a new chat dialog gui is suppose to open from the client 2�s side. This new chat dialog gui (jframe) is a thread so that if other users wishes to interact with client 2, another new chat dialog thread will appear!
    But in my case nope! Has soon as client 1 tries to establish a connection with client 2, boom. Error, connection refused: connect!!
    Now I been searching through Google trying to understand what this means and so far I found null� now I posted before asking what that means and someone told me it means that I forgot to close the sockets and input, output streams. But how can I close it when I cannot even establish a connection with client 2??
    Things I have tried:
    I tried inputting myself, the actual ip of client 2 and guess what� no luck
    I tried the client 2�s computer name, and same thing!
    I tried to create a whole new main class just so that I can open and close the sockets and input/output stream and nope, no luck at all..
    Now that you have a good understanding of my program. Here comes the code:
    I�l start with the user_window, which is the main menu as you call it: this jframe once opened, is suppose to create a server socket to listen for connections. If a connection is made, load the chatdialog gui thread�
    * user_window.java
    * Created on 10 February 2006, 11:50
    package icomm;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    * @author jonathan
    public class user_window extends javax.swing.JFrame implements WindowListener {
    protected String crnt_user;
    protected String crnt_ip;
    protected String dummy = "";
    /** Creates new form user_window */
    public user_window() {
    initComponents();
    listeningSocket();
    addWindowListener( this );
    public user_window(String users_name)
    initComponents();
    addWindowListener( this );
    this.crnt_user = users_name;
    private void exit()
    MySQL_queries offline = new MySQL_queries();
    offline.off_status(crnt_user);
    JOptionPane.showMessageDialog(null, "you are about to close the program " + crnt_user, null, JOptionPane.ERROR_MESSAGE);
    MySQL_queries query = new MySQL_queries();
    query.off_status(crnt_user);
    query.reset_ip(crnt_user);
    System.exit(0);
    public void windowClosing(WindowEvent e)
         exit();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    try {
    Buddie_list =(javax.swing.JTree)java.beans.Beans.instantiate(getClass().getClassLoader(), "icomm.user_window_Buddie_list");
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    } catch (java.io.IOException e) {
    e.printStackTrace();
    label = new javax.swing.JLabel();
    demo = new javax.swing.JButton();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    Close = new javax.swing.JMenuItem();
    jMenu2 = new javax.swing.JMenu();
    profile = new javax.swing.JMenuItem();
    jMenu3 = new javax.swing.JMenu();
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().add(Buddie_list, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 230, 310));
    getContentPane().add(label, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 390, -1, -1));
    demo.setText("talk to shienna");
    demo.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    demoActionPerformed(evt);
    getContentPane().add(demo, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 360, -1, -1));
    jMenu1.setText("File");
    jMenu1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jMenu1ActionPerformed(evt);
    Close.setLabel("Close");
    Close.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    CloseActionPerformed(evt);
    jMenu1.add(Close);
    jMenuBar1.add(jMenu1);
    jMenu2.setText("Option");
    profile.setText("Edit Profile");
    profile.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    profileActionPerformed(evt);
    jMenu2.add(profile);
    jMenuBar1.add(jMenu2);
    jMenu3.setText("Help");
    jMenuBar1.add(jMenu3);
    setJMenuBar(jMenuBar1);
    pack();
    // </editor-fold>
    private void demoActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
    ChatDialog_c chatting = new ChatDialog_c(crnt_user, dummy);
    chatting.setTitle("I-comm");
    chatting.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chatting.setSize(360, 500);
    chatting.getSize();
    chatting.setLocation(420,200);
    chatting.setVisible(true);
    private void CloseActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void demo1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void show_chat_window()
    ChatDialog chat_gui = new ChatDialog();
    chat_gui.setTitle("chat");
    chat_gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chat_gui.setSize(366, 480);
    chat_gui.getSize();
    chat_gui.setLocation(420,200);
    chat_gui.setVisible(true);// TODO add your handling code here:
    private void log_offActionPerformed(java.awt.event.ActionEvent evt) {                                       
    private void locate_ip()
    try
    InetAddress a;
    a = InetAddress.getLocalHost(); //get ip addrees
    this.crnt_ip = a.getHostAddress(); //then store it in this variable
    catch(UnknownHostException e)
    JOptionPane.showMessageDialog(null, "Error, cant detect localhost", null, JOptionPane.ERROR_MESSAGE);
    public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {}
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
         public void windowOpened(WindowEvent e)
    locate_ip();
    MySQL_queries new_ip = new MySQL_queries();
    new_ip.update_ip(crnt_user, crnt_ip);
    JOptionPane.showMessageDialog(null,"hello " + crnt_user + " your ip is" + crnt_ip, null, JOptionPane.ERROR_MESSAGE);
    private void listeningSocket()
    ServerSocket serverSocket = null;
    boolean listening = true;
    try
    //listen in port 4444;
    serverSocket = new ServerSocket(4444);
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
    while(listening)
    try
    ChatDialog chat = new ChatDialog(serverSocket.accept());
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "could not open chat window", null, JOptionPane.ERROR_MESSAGE);
    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    private void profileActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new user_window().setVisible(true);
    Now for the chatdialog class: I forgot to mention that I have two versions of this class. One that is a thread and the other makes a connection to a thread, hope that makes sence�
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog_c extends javax.swing.JFrame implements WindowListener {
        protected String messege;
        private Socket socket = null;
        protected String ip2;
        private PrintWriter out = null;
        private BufferedReader in = null;
        private String user_name;
        private String status;
        /** Creates new form ChatDialog_c */
        public ChatDialog_c()
            initComponents();
            addWindowListener( this );
         public ChatDialog_c(String ip1)
            initComponents();
            addWindowListener( this );
            this.ip2 = ip1;
            //OptionPane.showMessageDialog(null, "error in closing sockdswdset " + ip2, null, JOptionPane.ERROR_MESSAGE);
         public ChatDialog_c(String user, String status)
            initComponents();
            addWindowListener( this );
            this.user_name = user;
        public void windowClosing(WindowEvent e)
            public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {
                try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
          public void windowOpened(WindowEvent e)
              MySQL_queries get_ip = new MySQL_queries();
              this.ip2 = get_ip.find_client(user_name);
               JOptionPane.showMessageDialog(null, user_name + ip2, null, JOptionPane.ERROR_MESSAGE);
                //create socket connection
                try
                    socket = new Socket ("Shienna", 4444);
                    out = new PrintWriter(socket.getOutputStream(), true);
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                catch(UnknownHostException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "unknown  " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "2 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
                 try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                while(true)
                    try
                        String line = in.readLine();
                        convo_txt.append(line);
                    catch(IOException x)
                        x.printStackTrace();
                        JOptionPane.showMessageDialog(null, "3 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            convo_txt = new javax.swing.JTextArea();
            jScrollPane2 = new javax.swing.JScrollPane();
            txt_messege = new javax.swing.JTextArea();
            send = new javax.swing.JButton();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            jMenu2 = new javax.swing.JMenu();
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jScrollPane1.setViewportView(convo_txt);
            getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 220, 280));
            txt_messege.setLineWrap(true);
            jScrollPane2.setViewportView(txt_messege);
            getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 330, 220, 70));
            send.setText("Send");
            send.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    sendActionPerformed(evt);
            getContentPane().add(send, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 420, -1, -1));
            jMenu1.setText("File");
            jMenu1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenu1ActionPerformed(evt);
            jMenuBar1.add(jMenu1);
            jMenu2.setText("Option");
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            pack();
        // </editor-fold>                       
        private void sendActionPerformed(java.awt.event.ActionEvent evt) {                                    
            String text = txt_messege.getText();
            out.println();
            txt_messege.setText(new String(""));
            convo_txt.append(text);
        private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ChatDialog_c().setVisible(true);
        }///////////////////////chat dialog thread/////////////////////
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog extends javax.swing.JFrame implements WindowListener, Runnable {
        protected String messege;
        private Socket client_user = null;
        /** Creates new form ChatDialog */
        public ChatDialog()
            initComponents();
            addWindowListener( this );
        public ChatDialog(String txt_messege)
            initComponents();
            addWindowListener( this );
            this.messege = txt_messege;
         public ChatDialog(Socket user)
             initComponents();
             addWindowListener( this );
             this.client_user = user;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured ";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                   //send data back to user
                   out.println(messege);
                   //append data on the text field
                   convo_txt.append(messege + "\n");
                   //chat_gui.setVisible(true);
                   //-=inputs = new ChatDialog(messege);
               //out.close();
                //in.close();
                //client_user.close();
            catch (IOException e)
                //error messege
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, error + e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        }If I can sort this problem out I would of completed the main part of my program. I have spent days on this and hope that anyone of you guys can take the time out and help me with my current situation. Thanks

    update:
    i have managed to sort out the connection refused
    i know have anotehr problem: both client2 program freezes as soon as client 1 tries to initiate a connection to client 2!!!!!!!!
    when client 2 logs into teh system. it freezes as soon as i press the button! but when client 1 attempts to conenct to client 2, client 2's program stops freezing and the chatdialog comes up showing nothing and freezes! my chadialog is suppose to show a file menu i made but it doesnt,. both clients freezes at this point. no error messeges occur...

Maybe you are looking for

  • Where are the front USB ports on the HP Envy 700-210 Desktop?

    I bought the Envy 700-210 desktop because it has so many USB ports.   However, I can only find 8 - 2 on top and 6 in the back.   According to the specifications, there are supposed to be some in the front.   Do I have to take something apart to find

  • Need a Tool to Display When a Program Was Last Used

    Is there an SAP tool that tells when a program was last ran? I need to terminate some custom programs but unsure of which programs are not being used. Is there anything in SAP that I can use to tell me when a program was last used i.e., 6 months ago,

  • Air StageWebView html5 content vs native browser performance

    I'm using StageWebView for displaying a html5 contents (a simple game) in AIR mobile app. On some devices with Android 4.4, Nexus 4 for ex., html5 in StageWebView has 10 FPS instead of 50-60 in mobile Google Chrome on same device! But StageWebView us

  • Rename a column name

    Hi All, Can rename a column name permanantly.? Please clarify

  • Keep alive TCP setting for port 3998 to avoid fw timeout?

    Hello, in our new DS6.1 env, replication between the master DS is using port 3998 through several firewalls. If there are no changes to the DB (we are still testing), the connection seems to time out on the firewall and the status of the remote maste