-1

I've just started with both java and networking with servers and clients. Although i understand the basics of whats going on, i was struggling to put it all together and do what i wanted to do in the title. I was able to make this to send a message to the server, however i was wondering how i'd turn the message into a input string from the user, and also how id send multiple messages between the client and server thanks

SERVER

import java.io.*;
import java.net.*;

public class Server {

//Main Method:- called when running the class file.
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on.
    int portNumber = 15882;
    try{
        //Setup the socket for communication and accept incoming communication
        ServerSocket serverSoc = new ServerSocket(portNumber);
        Socket soc = serverSoc.accept();

        //Catch the incoming data in a data stream, read a line and output it to the console
        DataInputStream dataIn = new DataInputStream(soc.getInputStream());
        System.out.println("--> " + dataIn.readUTF());

        //Remember to close the socket once we have finished with it.
        soc.close();
    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing message to the console
        System.out.println("Error --> " + except.getMessage());
    }
}}

CLIENT

import java.io.*;
import java.net.*;


public class Client {

//Main Method:- called when running the class file.
public static void main(String[] args){ 

    //Portnumber:- number of the port we wish to connect on.
    int portNumber = 15882;
    //ServerIP:- IP address of the server.
    String serverIP = "localhost";

    try{
        //Create a new socket for communication
        Socket soc = new Socket(serverIP,portNumber);

        //Create the outputstream to send data through
        DataOutputStream dataOut = new DataOutputStream(soc.getOutputStream());

        //Write message to output stream and send through socket
        dataOut.writeUTF("Hello other world!");
        dataOut.flush();

        //close the data stream and socket 
        dataOut.close();
        soc.close();
    }
    catch (Exception except){
        //Exception thrown (except) when something went wrong, pushing message to the console
        System.out.println("Error --> " + except.getMessage());
    }
}}
LW001
  • 2,452
  • 6
  • 27
  • 36
man22
  • 35
  • 6

1 Answers1

0

There are some "problems" with your code.

  1. You should only close the ServerSocket if you are done.
  2. You should handle the newly connected client inside a thread to allow multiple clients to simultaniously "send messages".

1.

you could easily wrap your code inside an while loop.

boolean someCondition = true;
try{
    //Setup the socket for communication and accept incoming communication
    ServerSocket serverSoc = new ServerSocket(portNumber);
    // repeat the whole process over and over again.
    while(someCondition) {
        Socket soc = serverSoc.accept();

        //Catch the incoming data in a data stream, read a line and output it to the console
        DataInputStream dataIn = new DataInputStream(soc.getInputStream());
        System.out.println("--> " + dataIn.readUTF());
    }

    //Remember to close the socket once we have finished with it.
    soc.close();
}

Now your programm should continue to accept clients. But only one at a time. You can now terminate the Server by stopping the programm or by changing the someCondition to false and accepting the next client.

A bit more advanced would be, to shutdown the ServerSocket to stop the programm and catching the exception inside the while loop.


2.

To allow multiple clients to be handled simultaniously, you should pack the handle part into another Thread.

private ExecutorService threadPool = Executors.newCachedThreadPool();

boolean someCondition = true;
try{
    //Setup the socket for communication and accept incoming communication
    ServerSocket serverSoc = new ServerSocket(portNumber);
    // repeat the whole process over and over again.
    while(someCondition) {
        Socket soc = serverSoc.accept();

            //Catch the incoming data in a data stream, read a line and output it to the console in a new Thread.
        threadPool.submit(() -> {
            DataInputStream dataIn = new 
            DataInputStream(soc.getInputStream());
            System.out.println("--> " + dataIn.readUTF());
        }
    }

    //Remember to close the socket once we have finished with it.
    soc.close();
}

The part inside the threadPool.submit block could be specified as an custom instance of the Runnable interface of as an method, to call it using method reference.
I assumed you are knowing about ThreadPools. They have multiple advantages over Threads

This should get you going for any number of clients.

Note: This is not good designed, but it is for demonstrational porpurses only.

Thorben Kuck
  • 1,092
  • 12
  • 25