0

I want to know about my socket code and how will it affect my server hardware and other software

I have a linux server with static IP address.

I want to send data from lot of clients to this server using sockets

This is my server side code for the socket

import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketExample implements Runnable {

    public static void main(String[] args) {
        ServerSocketExample start = new ServerSocketExample();
        start.run();
    }

    @Override
    public void run() {
        try {
            ServerSocket ss = new ServerSocket(6664);
            Socket s = ss.accept();
            DataInputStream dis = new DataInputStream(s.getInputStream());
            String  str = (String) dis.readUTF();
            System.out.println("This: 1: "+str);
            if (str != null && !str.trim().equals("")) {
                processData(str);
            }
            s.close();
            ss.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            run();
        }
    }

    private void processData(String data) {
        System.out.println("This: 3: " + data);
    }
}

I want to know how this code may backfire me. Will this affects the server in any way?

Is there any better alternative?

Is this a better option?

Class 1.

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class NetworkService implements Runnable {
   private final ServerSocket serverSocket;
   private final ExecutorService pool;

   public NetworkService(int port, int poolSize) throws IOException {
     serverSocket = new ServerSocket(port);
     pool = Executors.newFixedThreadPool(poolSize);
   }

   public void run() {
       try {
           while (true) {
             pool.execute(new Handler(serverSocket.accept()));
           }
       } catch (IOException ex) {
           pool.shutdown();
       }
   }

}

Class 2.

import java.io.DataInputStream;
import java.net.Socket;

class Handler implements Runnable {
    private final Socket socket;

    Handler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            String str = (String) dis.readUTF();
            System.out.println("This: 1: "+str);
            processData(str);
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void processData(String data) {
        System.out.println("This: " + data);
    }
}
  • 2
    This will handle only the first connection then stop. – Xvolks Sep 06 '17 at 13:42
  • 1
    "Will this affect the server in any way" -> Yes. It will open a network port. Also, since your implementation is recursive, you will eventually run into a `StackOverflowError`. I would recommend some [tutorials on sockets](https://docs.oracle.com/javase/tutorial/networking/sockets/index.html). Normally you want to start a new Thread (or even better - use some [`ExecutorService`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html)) to process the incoming data. Otherwise new connections are blocked until data processing has completed. – Turing85 Sep 06 '17 at 13:50
  • 1
    This will only handle one *command*. `readUTF()` does not return null, and unless you're planning on sending blank strings it doesn't return those either. So why test for them? – user207421 Sep 06 '17 at 18:06
  • @Turning85 I have updated the question with a possible solution. Can you please confirm – Sylvester Das Sep 07 '17 at 11:43
  • @Turing85 I am sorry to bother you. But it is important for me to get this verified. – Sylvester Das Sep 09 '17 at 11:47

2 Answers2

0

If you are trying to make a server that takes in multiple clients you have 2 choices. Learn about multi threaded applications or learn about using a selector in the java.nio library.

How to use a selector for multiple users

Multiple thread application

I personally recommend the selector, it is more advanced but it takes less resources which will make it easier for your server.

Hope this helps.

user7922501
  • 420
  • 1
  • 5
  • 12
0

Your class 1 is an issue, your class 2 is mostly correct. Your issues in class 1 include:

  1. You only need 1 ServerSocket to receive all the client Sockets

    public class NetworkService{
    
    static final int PORT = 1978;
    
    public static void main(String args[]) {
    ServerSocket serverSocket = null;
    Socket socket = null;
    
    try {
        serverSocket = new ServerSocket(PORT);
    } catch (IOException e) {
        e.printStackTrace();
    
    }
    while (true) {
        try {
            socket = serverSocket.accept();
        } catch (IOException e) {
            System.out.println("I/O error: " + e);
        }
        // new thread for a client
        new Handler(socket).start();
    }
    }
    }
    

    If you want to make it a separate class by all means, that implements Runnable I don't suggest it but by all means.

I have never worked with DataInputStream for reading and writing to using a socket I use BufferedReader for reading & PrintWriter for writing. For use on how to do this oracle gave a tutorial on sockets. This is an example of a server with BufferedReader and PrintWriter

Avi
  • 17
  • 6