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 9161511
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T13:58:58+00:00 2026-06-17T13:58:58+00:00

I have been working on an instant messenger in only java code for a

  • 0

I have been working on an instant messenger in only java code for a while now. I am able to get it to work only if I am running the server and the client on the same computer then they communicate. But I cant get 2 different computers to connect to the same server and communicate. I have looked at many examples and I still dont understand what needs to be changed. I will show the code below most of it can be ignored only the network part needs to be looked at. The sever connection is at the bottom of the client code. I am a beginner and I appreciate any help. Thanks.

Client Code:

import javax.swing.*;
import javax.swing.text.DefaultCaret;

import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.Date;
import java.net.*;
import java.io.*;



public class NukeChatv3 extends JFrame
{

private JTextArea showtext;
private JTextField usertext;
private String hostname;
private Socket connectionsock;
private BufferedReader serverinput;
private PrintWriter serveroutput;
private int port;


private static final long serialVersionUID = 1L;

private class entersend implements KeyListener
{
      public void keyTyped ( KeyEvent e )
      {  

      }  
      public void keyPressed ( KeyEvent e)
      {  
          String text = usertext.getText();

          if(e.getKeyCode()== KeyEvent.VK_ENTER)
          {
              if (usertext.getText().equals(""))
                    return;
                else
                {
                    //try{
                    serveroutput.println(text);

                    usertext.setText("");
                    //showtext.append("[" + ft.format(dNow) + "]" + "\n" + "UserName: " + serverdata +"\n\n");
                    //}
                    /*catch(IOException in)
                    {
                        showtext.append(in.getMessage());
                    }*/

                }
          }
          else 
              return;
      }  
      public void keyReleased ( KeyEvent e )
      {  

      } 
}

private class sender implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if (usertext.getText().equals(""))
            return;
        else
        {
            Date dNow = new Date( );
            SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
            String text = usertext.getText();
            usertext.setText("");

            //* Send message to server



            showtext.append(ft.format(dNow) + "\n" + "UserName: " + text +"\n\n");
        }
    }
}

private class startconnection implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        clientconnection connect = new clientconnection();
        connect.start();
    }
}

private class CheckOnExit implements WindowListener
{
    public void windowOpened(WindowEvent e)
    {}

    public void windowClosing(WindowEvent e)
    {
        ConfirmWindow checkers = new ConfirmWindow( );
        checkers.setVisible(true);
    }

    public void windowClosed(WindowEvent e)
    {}

    public void windowIconified(WindowEvent e)
    {}

     public void windowDeiconified(WindowEvent e)
    {}

    public void windowActivated(WindowEvent e)
    {}

    public void windowDeactivated(WindowEvent e)
    {}
}


private class ConfirmWindow extends JFrame implements ActionListener
{

    private static final long serialVersionUID = 1L;

    public ConfirmWindow( )
    {
        setSize(200, 100);
        getContentPane( ).setBackground(Color.LIGHT_GRAY);
        setLayout(new BorderLayout( ));

        JLabel confirmLabel = new JLabel(
                       "Are you sure you want to exit?");
        add(confirmLabel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel( );
        buttonPanel.setBackground(Color.GRAY);
        buttonPanel.setLayout(new FlowLayout( ));

        JButton exitButton = new JButton("Yes");
        exitButton.addActionListener(this);
        buttonPanel.add(exitButton);

        JButton cancelButton = new JButton("No");
        cancelButton.addActionListener(this);
        buttonPanel.add(cancelButton);

        add(buttonPanel, BorderLayout.SOUTH);
    }

    public void actionPerformed(ActionEvent e) 
    {
        String actionCommand = e.getActionCommand( );

        if (actionCommand.equals("Yes")) 
            System.exit(0);
        else if (actionCommand.equals("No"))
            dispose( );
        else
            System.out.println("Unexpected Error in Confirm Window.");
    }
}


public static void main(String[] args) 
{

    NukeChatv3 nuke = new NukeChatv3();
    nuke.setVisible(true);

}

public NukeChatv3()
{       
        setTitle("NukeChat v3");
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setSize(550, 400);
        setResizable(false);
        addWindowListener(new CheckOnExit());
        addWindowListener(new WindowAdapter(){
            public void windowOpened(WindowEvent e){
                usertext.requestFocus();
            }
        });
        getContentPane().setBackground(Color.BLACK);
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        showtext = new JTextArea(15, 35);
        showtext.setEditable(false);
        showtext.setLineWrap(true);
        DefaultCaret caret = (DefaultCaret)showtext.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);


        JScrollPane scrollbar = new JScrollPane(showtext);
        scrollbar.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollbar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        c.anchor = GridBagConstraints.FIRST_LINE_START;
        //c.gridwidth = 2;
        c.insets = new Insets(20, 20, 20, 20);
        c.weightx = .5;
        c.weighty = .5;
        c.gridx = 0;
        c.gridy = 0;
        add(scrollbar, c);

        usertext = new JTextField(35);

        usertext.requestFocusInWindow();
        usertext.addKeyListener(new entersend());
        //c.gridwidth = 1;
        c.insets = new Insets(0, 20, 0, 0);
        c.weightx = .5;
        c.gridx = 0;
        c.gridy = 1;
        add(usertext, c);

        JPanel empty = new JPanel();
        c.gridx = 1;
        c.gridy = 0;
        empty.setLayout(new GridLayout(2,1));

        JButton test1 = new JButton("test1");
        empty.add(test1);

        JButton test2 = new JButton("test2");
        empty.add(test2);

        add(empty, c);

        JButton send = new JButton("Send");
        send.addActionListener(new sender());
        c.ipady = -5;
        c.insets = new Insets(0, 0, 20, 0);
        c.gridx = 1;
        c.gridy = 1;
        add(send, c);

        JMenu menu = new JMenu("File");
        JMenuItem connection = new JMenuItem("Connect");
        connection.addActionListener(new startconnection());
        menu.add(connection);

        JMenuBar bar = new JMenuBar();
        bar.add(menu);
        setJMenuBar(bar);



}

private class clientconnection  extends Thread
{
    public void run()
    {
        try
        {
            // Set host name and port//
            hostname = "localhost";
            port = 16666;

            // connect to socket of the server//
            connectionsock = new Socket(hostname, port);

            // set up client input from server//
            serverinput = new BufferedReader(new InputStreamReader(connectionsock.getInputStream()));

            // set up client output to server//
            serveroutput = new PrintWriter(connectionsock.getOutputStream(), true);

            // set up a looping thread to constantly check if server has sent anything 
            String serverdata = "";

            while ((serverdata = serverinput.readLine()) != null)
            {
                Thread.sleep(500);
                Date dNow = new Date( );
                SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
                showtext.append("[" + ft.format(dNow) + "]" + "\n" +"Recieved from server: \n" + "UserName: " + serverdata +"\n\n");
            }

        }

        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
        catch(InterruptedException inter)
        {
            showtext.append("Unexpected interruption\n\n");
        }
    }


}

}

Server Code :

import java.net.ServerSocket;
import java.io.*;
import java.net.Socket;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;



public class servertest extends JFrame
{

private JButton start;
private JTextArea text;
private BufferedReader clientinput;
private PrintWriter clientoutput;

private class listen implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        connection connect = new connection();
        connect.start();
    }
}

public servertest ()
{
    setSize(400,300);
    setLayout(new BorderLayout());
    start = new JButton("Start");
    start.addActionListener(new listen());
    add(start, BorderLayout.SOUTH);

    text = new JTextArea(6, 10);
    text.setEditable(false);
    add(text, BorderLayout.CENTER);
}
private class connection extends Thread
{
    public void run()
    {
    try
    {
        // Sets up a server socket with set port//
        text.setText("Waiting for connection on port 16666");
        ServerSocket serversock = new ServerSocket(16666);

        // Waits for the Client to connect to the server//
        Socket connectionsock = serversock.accept();

        // Sets up Input from the Client to go to the server//
        clientinput = new BufferedReader(new InputStreamReader(connectionsock.getInputStream()));

        // Sets up data output to send data from server to client//
        clientoutput = new PrintWriter(connectionsock.getOutputStream(), true);

        // Test server to see if it can perform a simple task//
        text.setText("Connection made, waiting to client to send there name");
        clientoutput.println("Enter your name please.");

        // Get users name//
        String clienttext = clientinput.readLine();

        // Reply back to the client//
        String replytext = "Welcome " + clienttext;
        clientoutput.println(replytext);
        text.setText("Sent: " + replytext);

        while ((replytext = clientinput.readLine()) != null)
        {
            clientoutput.println(replytext);
            text.setText("Sent: " + replytext);
        }

        // If you need to close the Socket connections
        // clientoutput.close();
        // clientinput.close();
        // connetionsock.close();
        // serversock.close();

    }

    catch(IOException e)
    {
        System.out.println(e.getMessage());
    }
    }
}

public static void main(String[] args)
{
    servertest test = new servertest();
    test.setVisible(true);
}
  • 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-17T13:58:59+00:00Added an answer on June 17, 2026 at 1:58 pm

    In your client code, specify correct hostname/IP address where server is running:

    private class clientconnection  extends Thread
    {
        public void run()
        {
            try
            {
                // Set host name and port//
                hostname = "localhost"; //<---- Change this to server IP address
                port = 16666;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been working with SQL Server as a Developer a while. One thing
I have been working on a widet for a while now and I have
I have been working on an application in Xcode for a while now and
I have been working on a large java application. It is quite parallel, and
I have been working with Zend for a few months now and am at
I've been working this issue for a while now and I am open to
I have been working on this project for quite a while and still I
I have been working with jquery-ui's sortable demo for a while. On looking closely,
I'm working on a partner's repository code, and have been using the github.com web
Have been working on a Tower Defense game for iOS for some time now.

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.