Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Can anyone tell me how to create a basic Java Server which can connect multiple people? It should send data to every client who’s connected when one of the clients receives data. 

1 Answer

0 votes
by (19.7k points)

Please check the code below:

import java.net.*;

import java.io.*;

public class KnockKnockServer {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;

        try {

            serverSocket = new ServerSocket(4444);

        } catch (IOException e) {

            System.err.println("Could not listen on port: 4444.");

            System.exit(1);

        }

        Socket clientSocket = null;

        try {

            clientSocket = serverSocket.accept();

        } catch (IOException e) {

            System.err.println("Accept failed.");

            System.exit(1);

        }

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

        BufferedReader in = new BufferedReader(

                new InputStreamReader(

                clientSocket.getInputStream()));

        String inputLine, outputLine;

        KnockKnockProtocol kkp = new KnockKnockProtocol();

        outputLine = kkp.processInput(null);

        out.println(outputLine);

        while ((inputLine = in.readLine()) != null) {

             outputLine = kkp.processInput(inputLine);

             out.println(outputLine);

             if (outputLine.equals("Bye."))

                break;

        }

        out.close();

        in.close();

        clientSocket.close();

        serverSocket.close();

    }

}

Interested in Java? Check out this Java tutorial by Intellipaat.  

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...