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

  • Home
  • SEARCH
  • 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 9219211
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T03:03:40+00:00 2026-06-18T03:03:40+00:00

A few days ago i tried to create a server – client or client

  • 0

A few days ago i tried to create a server – client or client Server as an experiment to learn about socket using a thread but then someone told me that i should use swingWorker. I did some research how to use and have implemented it in as practice but it still doesn’t work. the swingWorker thread doesn’t look like it is running even tho i get a connection and have used .excute(). If you guys can help spot where i am doing wrong that will be great. SwingWorker class is in the startSever() and startClient() method.

    private void startServer() {
        SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
        protected Void doInBackground() {
            try {
                listeningSocket = new ServerSocket(port);
                System.out.println("waiting for connection");
                connection = listeningSocket.accept();
                connected = true;
                System.out.println("Connected");
                String incomeMessage =null;
                while(connected){
                inStream = connection.getInputStream();
                    inDataStream = new DataInputStream(inStream);
                    if (myMessage !=null){
                        outStream = connection.getOutputStream();
                        outDataStream = new DataOutputStream(outStream);
                    outDataStream.writeUTF(myMessage);
                    }

                    if((incomeMessage = inDataStream.readUTF())!=null){
                        clientMessage = incomeMessage;
                        publish(clientMessage);
                        incomeMessage =null;
                    }
                }
            } catch (IOException e) {
                clientMessage = "Connection Lost";
            }
        return null;
    }           
runningServer.execute();
}
  • 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-18T03:03:41+00:00Added an answer on June 18, 2026 at 3:03 am

    Here’s a VERY basic example.

    Basically, because you program requires asynchronous communications (that is, you need to be able to read from the socket AND write to it at the same time), you need to offload each stream to a separate thread.

    The management process of this example is, well, no existent. Realistically, you should have some kind of “connection” manager that would be able to cleanly close the output and input threads so that, for example, when the user types “bye”, the output thread would be able to tell the connection manager that the connection should be terminated. It would then tell the input thread to stop reading any new message and terminate…

    Client

    public class Client {
    
        public static void main(String[] args) {
    
            try {
                Socket master = new Socket("localhost", 8900);
                new Thread(new InputHandler(master)).start();
                new Thread(new OuputHandler(master)).start();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
    
        }
    
        public static class InputHandler implements Runnable {
    
            private Socket socket;
    
            public InputHandler(Socket socket) {
                this.socket = socket;
            }
    
            @Override
            public void run() {
                boolean commune = true;
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    while (commune) {
                        String text = reader.readLine();
                        System.out.println("\n<server> " + text);
                        if (text.toLowerCase().equals("bye")) {
                            commune = false;
                        }
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        reader.close();
                    } catch (Exception e) {
                    }
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    
        public static class OuputHandler implements Runnable {
    
            private Socket socket;
    
            public OuputHandler(Socket socket) {
                this.socket = socket;
            }
    
            @Override
            public void run() {
                boolean commune = true;
                BufferedWriter writer = null;
                try {
                    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    Scanner scanner = new Scanner(System.in);
                    while (commune) {
                        System.out.print("> ");
                        String text = scanner.nextLine();
                        writer.write(text);
                        writer.newLine();
                        writer.flush();
                        if (text.equalsIgnoreCase("bye")) {
                            commune = false;
                        }
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        writer.close();
                    } catch (Exception e) {
                    }
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
    

    Server

    public class Server {
    
        public static void main(String[] args) {
    
            try {
                ServerSocket master = new ServerSocket(8900);
                Socket socket = master.accept();
                new Thread(new InputHandler(socket)).start();
                new Thread(new OuputHandler(socket)).start();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
    
        }
    
        public static class InputHandler implements Runnable {
    
            private Socket socket;
    
            public InputHandler(Socket socket) {
                this.socket = socket;
            }
    
            @Override
            public void run() {
                boolean commune = true;
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    while (commune) {
                        String text = reader.readLine();
                        System.out.println("\n<client> " + text);
                        if (text.toLowerCase().equals("bye")) {
                            commune = false;
                        }
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        reader.close();
                    } catch (Exception e) {
                    }
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
        public static class OuputHandler implements Runnable {
    
            private Socket socket;
    
            public OuputHandler(Socket socket) {
                this.socket = socket;
            }
    
            @Override
            public void run() {
                boolean commune = true;
                BufferedWriter writer = null;
                try {
                    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    Scanner scanner = new Scanner(System.in);
                    while (commune) {
                        System.out.print("> ");
                        String text = scanner.next();
                        writer.write(text);
                        writer.newLine();
                        writer.flush();
                        if (text.equalsIgnoreCase("bye")) {
                            commune = false;
                        }
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        writer.close();
                    } catch (Exception e) {
                    }
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
    

    Update (whine)

    While I have your source code in front of me…

    There should very, very, rarely be a need to do textMessage.addKeyListener(this)

    Because you are using a JTextField, you should be using a ActionListener instead. There are a a number of important reasons for this, but for you, the main one would be the fact that a “accept” action is Look and Feel dependent. While most systems do use Enter as there “accept” action, is not a guarantee.

    Have a look at How to Write a Action Listener for more information

    Given the general complexity of what you are trying to do, +1 for a overall good attempt!

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

Sidebar

Related Questions

Few days ago I tried to create a system that jQuery will enable me
I am started using MongoDB few days ago. Everything is fine with MongoDB but
few days ago i asked about how to get all running processes in the
few days ago i read tutorial about GenericRepository and Unit Of Work patterns http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
A few days ago I set up a small development server. Running on Windows
A few days ago I posted a thread asking on how to find the
A few days ago I asked this question about jquery ajax function invoking action
I just learned about XSL and XSLT a few days ago and now I'm
I started using Hukkster.com a few days ago. It is really fast and accurate.
Last Updated: 2009-08-11 2:30pm EDT A few days ago I posted this question about

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.