Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9203271
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:26:11+00:00 2026-06-17T23:26:11+00:00

Hi I am trying create a small client server or server client chat message

  • 0

Hi I am trying create a small client server or server client chat message application as an experiment and to gain some knowledge and experience in java socket. I have been having problem sending and receiving messages. I do get a connection and the Thread looks like it is running but it wouldn’t send or receive a message to each to other. I am not sure if the connection automatically closes once it connects but i know i am doing something wrong but i cant seem to find it. If you can help me that would be great. the code is below


Server:

public class ServerGUI extends JFrame implements KeyListener{
/**
 * 
 */
private static final long serialVersionUID = 1L;
/*private JButton sendButton = new JButton("send");
private JButton connectButton = new JButton("Connect");
private JButton disconnectButton = new JButton("Disconnect");*/
private JTextField textMessage = new JTextField();
private JLabel connectMessageLabel = new JLabel("Waiting for Client");
private JTextArea messageTextArea = new JTextArea();
private JPanel buttonPanel = new JPanel();
private JPanel messageLabelPanel = new JPanel();
private JPanel messageTextAreaPanel = new JPanel();
private JPanel content = new JPanel();
private static String thisName= "<Me> ";
private static String friendLabel= "<My Friend> ";
private static JFrame serverFrame = new JFrame();
private int port= 0;
private String clientMessage=null;
private String myMessage=null;
private ServerSocket listenSocket;
private Socket connection;
private InputStream inStream;
private DataInputStream inDataStream;
private OutputStream outStream;
private DataOutputStream outDataStream;
private Thread runChatServer;

//----------------------------------------------------------------------------------------------
//-------------------------serverGui------------------------------------------------------------
@SuppressWarnings("deprecation")
public ServerGUI(int port){
    this.port = port;
    messageLabelPanel.setLayout(new GridLayout(1, 1, 1, 1));
    messageLabelPanel.add(connectMessageLabel);
    buttonPanel.setLayout(new GridLayout(1, 1, 1, 1));
    //buttonPanel.add(connectButton);
    //buttonPanel.add(sendButton);
    buttonPanel.add(textMessage);
    textMessage.addKeyListener(this);
    textMessage.setForeground(Color.BLACK);
    messageTextAreaPanel.setLayout(new BorderLayout(1, 1));
    messageTextAreaPanel.add(buttonPanel, BorderLayout.SOUTH);
    messageTextAreaPanel.add(messageLabelPanel,BorderLayout.NORTH);
    messageTextAreaPanel.add(new JScrollPane(messageTextArea),BorderLayout.CENTER);
    messageTextArea.setDisabledTextColor(Color.BLACK);
    messageTextArea.enable(false);
    content.setLayout(new GridLayout(1, 1, 1, 1));
    content.add(messageTextAreaPanel);
    content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    serverFrame.setContentPane(content);
    serverFrame.pack();
    serverFrame.setSize(450,550);
    serverFrame.setLocationRelativeTo(null);
    serverFrame.setVisible(true);
    serverFrame.setTitle("Chat Server");
    serverFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    startServer();
}

//-----------------------------------------------------------------------------------------------------
//-------------------------------keyPressed------------------------------------------------------------
public void startServer(){
    System.out.println("startServer");
    try{
        listenSocket = new ServerSocket(port);
        System.out.println("Waiting for client");
        connection = listenSocket.accept();
        System.out.println("Client Found");
        connectMessageLabel.setText("Client Found");
        runChatServer = new Thread(serverListeningAndChatting);
        runChatServer.start();
    }
    catch (Exception ex){

        System.out.println("No Connection Found");
        connectMessageLabel.setText("No Connection Found");
    }
}
//-----------------------------------------------------------------------------------------------------
//-------------------------------listening------------------------------------------------------------
public void listening(){
    System.out.println("listening");
    try{
        inStream = connection.getInputStream();
        inDataStream = new DataInputStream(inStream);
        clientMessage = inDataStream.readUTF();
        if (clientMessage!= null){
            messageTextArea.append(clientMessage + "\n");
            clientMessage = null;
        }
    }catch(Exception ex){System.out.println(ex);}
}
//-----------------------------------------------------------------------------------------------------
//-------------------------------sendMessage------------------------------------------------------------
public void sendMessage(){
    System.out.println("sendMessage");
    try{
        outStream = connection.getOutputStream();
        outDataStream = new DataOutputStream(outStream);

        if (myMessage!=null){
            outDataStream.writeUTF(myMessage);
            myMessage=null;
        }
    }catch(Exception ex){System.out.println("Message Failed");}
}
//-----------------------------------------------------------------------------------------------------
//-------------------------------keyPressed------------------------------------------------------------
public void keyPressed(KeyEvent e) {
    if(e.getKeyChar() == KeyEvent.VK_ENTER){
        myMessage = friendLabel+ textMessage.getText();
        messageTextArea.append(thisName+textMessage.getText() +"\n");
        textMessage.setText("");
    }
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}

//-----------------------------------------------------------------------------------------------------
//-------------------------------main------------------------------------------------------------
public static void main (String args[]){
    new ServerGUI(8901);
}

//-----------------------------------------------------------------------------------------------------
//-------------------------------run------------------------------------------------------------
public Runnable serverListeningAndChatting = new Runnable(){
    public void run() {
        while (true){
            System.out.println("Running");
            listening();
            sendMessage();
        }
    }
};

}

Client:

public class ClientGUI extends JFrame implements KeyListener{
/**
 * 
 */
private static final long serialVersionUID = 1L;
private JTextField textMessage = new JTextField();
private JLabel connectMessageLabel = new JLabel("Connection failed or no Server is available");
private JTextArea messageTextArea = new JTextArea();
private JPanel buttonPanel = new JPanel();
private JPanel messageLabelPanel = new JPanel();
private JPanel messageTextAreaPanel = new JPanel();
private JPanel content = new JPanel();
private static String thisName= "<Me> ";
private static String friendLabel= "<My Friend> ";
private static JFrame clientFrame = new JFrame();
private int port =0;
private String remoteMachine =null;
private String clientMessage=null;
private String myMessage=null;
private Socket connection;
private InputStream inStream;
private DataInputStream inDataStream;
private OutputStream outStream;
private DataOutputStream outDataStream;
private Thread runChatClient;
//-----------------------------------------------------------------------------------------------------
//-------------------------------ClientGUI------------------------------------------------------------

@SuppressWarnings("deprecation")
public ClientGUI(String remoteMachine, int port){
    this.port= port;
    this.remoteMachine = remoteMachine;
    messageLabelPanel.setLayout(new GridLayout(1, 1, 1, 1));
    messageLabelPanel.add(connectMessageLabel);
    buttonPanel.setLayout(new GridLayout(1, 1, 1, 1));
    //buttonPanel.add(connectButton);
    //buttonPanel.add(sendButton);
    buttonPanel.add(textMessage);
    textMessage.addKeyListener(this);
    textMessage.setForeground(Color.BLACK);
    messageTextAreaPanel.setLayout(new BorderLayout(1, 1));
    messageTextAreaPanel.add(buttonPanel, BorderLayout.SOUTH);
    messageTextAreaPanel.add(messageLabelPanel,BorderLayout.NORTH);
    messageTextAreaPanel.add(new JScrollPane(messageTextArea),BorderLayout.CENTER);
    messageTextArea.setDisabledTextColor(Color.BLACK);
    messageTextArea.enable(false);
    content.setLayout(new GridLayout(1, 1, 1, 1));
    content.add(messageTextAreaPanel);
    content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    clientFrame.setContentPane(content);
    clientFrame.pack();
    clientFrame.setSize(450,550);
    clientFrame.setLocationRelativeTo(null);
    clientFrame.setVisible(true);
    clientFrame.setTitle("Chat Client");
    clientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    startClient();

}

//-----------------------------------------------------------------------------------------------------
//-------------------------------startClient------------------------------------------------------------
public void startClient(){
    System.out.println("startClient");
    try{
        System.out.println("Connecting to Server");
        connection = new Socket(remoteMachine, port);
        System.out.println("Server Found");
        connectMessageLabel.setText("Server Found");
        runChatClient = new Thread(clientListeningAndChatting);
        runChatClient.start();
    }
    catch (Exception ex){
        System.out.println("No Connection Found");
        connectMessageLabel.setText("No Connection Found");
    }

}
//-----------------------------------------------------------------------------------------------------
//-------------------------------keyPressed------------------------------------------------------------
public void keyPressed(KeyEvent e) {
    if(e.getKeyChar() == KeyEvent.VK_ENTER){
        myMessage = friendLabel+ textMessage.getText();
        messageTextArea.append(thisName+textMessage.getText() +"\n");
        textMessage.setText("");
    }
}

//-----------------------------------------------------------------------------------------------------
//-------------------------------listening------------------------------------------------------------
public void listening(){
    System.out.println("listening");
    try{
        inStream = connection.getInputStream();
        inDataStream = new DataInputStream(inStream);
        clientMessage = inDataStream.readUTF();
        if (clientMessage!= null){
            messageTextArea.append(clientMessage + "\n");
            clientMessage = null;
        }
    }catch(Exception ex){System.out.println("Disconnected");}
}
//-----------------------------------------------------------------------------------------------------
//-------------------------------sendMessage------------------------------------------------------------
public void sendMessage(){
    System.out.println("sendMessage");
    try{
        outStream = connection.getOutputStream();
        outDataStream = new DataOutputStream(outStream);
        if (myMessage!=null){
            outDataStream.writeUTF(myMessage);
            myMessage=null;
        }
    }catch(Exception ex){System.out.println("Message Failed");}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
//-----------------------------------------------------------------------------------------------------
//-------------------------------main------------------------------------------------------------
public static void main (String args[]){
    new ClientGUI(null, 8901);
}

//-----------------------------------------------------------------------------------------------------
//-------------------------------run------------------------------------------------------------
public Runnable clientListeningAndChatting = new Runnable(){

    public void run() {
        System.out.println("Running");
        while (true){
            listening();
            sendMessage();
        }
    }
};
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T23:26:12+00:00Added an answer on June 17, 2026 at 11:26 pm

    The statement

    listenSocket.accept();
    

    is a blocking call is is blocking the EDT. This and any other network access calls should be handled by a SwingWorker. As Swing is single threaded, no events can be processed so no messages can be exchanged between the client & server.

    Use SwingWorker over Thread—it takes care of GUI interaction tasks.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to create a small server type application and have a question
I'm trying to create a small HTTP server in C# but I'm having some
I am trying to create a small Java application using Tomcat and am having
I'm trying to make my small multi client server run in a pthread so
I have a small server-client application that doesn't do very much (a client connects
I am trying to create a small pop-up in my Android application to let
Im trying to create a small application where a user submit personal info and
I am trying to create a small application where a user can drag an
I am trying to create a mobile version of a facebook chat client. I
I'm trying to write a small client server program. The Server is in C#,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.