I was creating a chat application in Java Swing/Socket Programming. The same when I created in non GUI app. it worked [url]http://www.daniweb.com/code/snippet448.html [/url]. But in GUI, they can't connect now. I have tried it thru many ways but still m getting errors for connection.
Can anyone can help me......

/*********************
ChatServer.java
**********************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

public class ChatServer extends JFrame implements ActionListener
{
    JPanel jpA = new JPanel();
    JTextArea txtA = new JTextArea(10,10);  
    JTextArea txtB = new JTextArea(10,10);  
    JButton send = new JButton("Send");
    JTextField status = new JTextField(20);

    int PORT = 8145;
    InputStream inStream;
    DataInputStream inDataStream;
    OutputStream outStream;
    DataOutputStream outDataStream;
    String message = "";
    ServerSocket sock = null;
    Socket conn = null;

    public ChatServer(String title){
        setTitle(title);
        Container c = this.getContentPane();            
        send.addActionListener(this);               
        jpA.add(txtA);
        jpA.add(send);
        jpA.add(txtB);      
        jpA.add(status);
        c.add(jpA);     
    }
    public void actionPerformed(ActionEvent ae){        
        if(ae.getSource()==send){   
            try{
                InetAddress HOST = InetAddress.getLocalHost();
                Socket sock = new Socket(HOST,PORT);
                outStream = conn.getOutputStream();
                outDataStream = new DataOutputStream (outStream);
                message = txtA.getText();
                outDataStream.writeUTF(message);            
                status.setText("Message have been sent");
            }catch(Exception e){status.setText(message);}
        }
    }
    public void connectClient(){
        try{
                sock = new ServerSocket(PORT);
                sock.accept();  
                message = "Client Connected";
                System.out.println(message);                
            }catch(Exception e){status.setText(message);System.out.println("Connection Problem..."+e);}
        status.setText(message);
    }
    public static void main(String args[]){
        ChatServer cs = new ChatServer("This is the Server");       
        cs.setVisible(true);
        cs.setSize(400,350);
        cs.connectClient();     
    }
}
/*********************
ChatClient.java
**********************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

public class ChatClient extends JFrame implements ActionListener
{
    JPanel jpA = new JPanel();
    JTextField tfa = new JTextField(15);
    JTextField tfb = new JTextField(5);
    JButton connect = new JButton("Connect");

    JTextArea txtA = new JTextArea(10,10);  
    JTextArea txtB = new JTextArea(10,10);  
    JButton send = new JButton("Send");
    JButton recieve = new JButton("Recieve");
    JTextField status = new JTextField(20);

    int PORT = 8145;    
    String HOST = "";
    InputStream inStream;
    DataInputStream inDataStream;
    OutputStream outStream;
    DataOutputStream outDataStream;
    String message = "";
    Socket sock = null;
    public ChatClient(String title){
        setTitle(title);
        Container c = this.getContentPane();        
        connect.addActionListener(this);
        send.addActionListener(this);
        recieve.addActionListener(this);
        jpA.add(tfa);
        jpA.add(connect);       
        jpA.add(txtA);
        jpA.add(send);
        jpA.add(recieve);
        jpA.add(txtB);      
        jpA.add(status);
        c.add(jpA);

    }
    public void actionPerformed(ActionEvent ae){
        if(ae.getSource()==connect){
            status.setText("Connecting.......");
            HOST = tfa.getText();           
            try{    
                sock = new Socket(HOST,PORT);
                inStream = sock.getInputStream ();
                inDataStream = new DataInputStream ( inStream );
                message = inDataStream.readUTF();               
                status.setText("You are connected");
            }catch(Exception e){status.setText(message);}
        }
        if(ae.getSource()==recieve){
            try{
                System.out.println("sock details: "+sock);
                inStream = sock.getInputStream ();
                System.out.println("sock inoutstream details: "+inStream);
                inDataStream = new DataInputStream ( inStream );
                message = inDataStream.readUTF();
                System.out.println("message is that : "+message);
                if(message==null)
                    txtB.setText("No message was recieved");
                else
                    txtB.setText(message);
            }catch(Exception e){status.setText(""+e);}
        }
    }public static void main(String args[]){
        ChatClient cc = new ChatClient("This is the Client");       
        cc.setVisible(true);
        cc.setSize(400,350);
    }
}

Dani AI

Generated

Short diagnosis and root causes: network I/O is being done on the Swing Event Dispatch Thread (so the UI freezes) and the Server never assigns the Socket returned by accept() to its conn field (the accept() return is ignored). The server's Send handler also creates a new Socket to localhost and then uses conn anyway, which produces null-output-stream/NPEs or connection resets. As suggested, this is fundamentally a threading/connection-management problem; also correctly pointed out that data must be read by a persistent listener rather than only when a button is pressed.

Concrete fixes and checklist

  • Run blocking calls (ServerSocket.accept, Socket.connect, readUTF()) off the EDT — use SwingWorker or a plain Thread. Update Swing components via SwingUtilities.invokeLater.
  • On the server assign the accepted socket: conn = serverSocket.accept(); — do not discard it.
  • Do not create a new Socket in the server's send handler. Use the existing connection's OutputStream and synchronize writes if multiple threads may write.
  • Start a dedicated reader thread on both sides that loops on readUTF() and posts messages to the UI; that avoids losing messages and blocking the interface.
  • Always handle IOException, close streams/sockets cleanly on disconnect, and check conn != null && !conn.isClosed() before sending.

Minimal pattern (illustrative, not full classes):

ServerSocket ss = new ServerSocket(PORT);
new Thread(new Runnable(){
  public void run(){
    try {
      conn = ss.accept(); // store accepted socket
      final DataInputStream in = new DataInputStream(conn.getInputStream());
      while (true) {
        final String msg = in.readUTF();
        SwingUtilities.invokeLater(new Runnable(){ public void run(){ txtB.append(msg + "\n"); }});
      }
    } catch(IOException ex){ /* handle/close */ }
  }
}).start();

// In send action: do NOT open new Socket; write to conn's stream on a background thread
new Thread(new Runnable(){ public void run(){
  try {
    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.writeUTF(txtA.getText()); out.flush();
    SwingUtilities.invokeLater(new Runnable(){ public void run(){ status.setText("Sent"); }});
  } catch(IOException e){ /* handle */ }
}}).start();

Caution: the "Connection reset" traces like those seen by usually mean the peer closed the socket or the protocol/handshake timing was wrong — persistent reader threads and correct socket ownership fix that.

Recommended Answers

All 5 Replies

It doesn't look well multithreaded ;) What's the error? I'm guessing it just locks up and never connects, right?

Not quite sure what it's doing, but looks to me like the he's trying to receive something by pushing a button. Anything sent over the network at any time except that it's available to the client just when the button is pushed is simply thrown away (or that's what it looks like).
There doesn't seem to be any code to handle sending data at all...
Nothing listening for network traffic, nothing listening for things to send.
That connection might be made but never do anything really useful.

I didn't even look too much at the code ;) I didn't see any multithreading in it, so I just guessed that was the problem. I created one like what I think he's trying to do with swing and it just locked up. It worked via console, but not swing. It was obviously a multithreading problem, but I just gave up on it ;)

so could you please tell me where i can implement the Threads or an idea of how to make the Client/Server recieve the buffer contents as soon as the data is sent from the Server/Client

set ip to:

InetAddress host = InetAddress.getLocalHost();
String diffHost = "";
Socket sock = new Socket(diffHost,PORT);
System.out.println("Chat Client Started");


& run client fallowing exception throw>>>>>>

run:
Chat Client Started

Enter your message here:
sdsds
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:185)
at java.net.SocketInputStream.read(SocketInputStream.java:199)
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:337)
at java.io.DataInputStream.readUTF(DataInputStream.java:589)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at chat.Client.main(Client.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.