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);
}
}