Java socket setSoTimeout and performance hit - java

I'd like to gracefully close the serversocket. I have so far this code:
#Override
public void init() throws IOException {
listener = new ServerSocket();
listener.setSoTimeout(1);
listener.setReuseAddress(true);
listener.bind(new InetSocketAddress(85));
clientProcessingPool = Executors.newFixedThreadPool(50);
while (!clientProcessingPool.isShutdown()) {
try {
Socket socket = listener.accept();
clientProcessingPool.submit(new StlExecutor(socket, this));
} catch (SocketTimeoutException e) {
} catch (Exception e) {
logger.error("", e);
e.printStackTrace();
}
}
listener.close();
}
public void stop() throws Exception {
clientProcessingPool.shutdownNow();
}
Is it reasonable to set so low SO_TIMEOUT? What is reasonable value then? What is the performance hit?

Related

Run thrift in new thread cant catch the exception

I run thrift in a thread like this:
public static void start() {
Runnable simple = new Runnable() {
public void run() {
TProcessor tprocessor = new MessageForwardsService.Processor<MessageForwardsService.Iface>(new MessageForwardsRpcInterface());
try {
simple(tprocessor);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread t = new Thread(simple);
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Thread uncaughtExceptionHandler catch a Exception**************************************************><><><><><><><><><<><><><><><");
System.out.println(e.getMessage());
e.printStackTrace();
}
});
t.start();
}
#SuppressWarnings("rawtypes")
public static void simple(MessageForwardsService.Processor processor) {
try {
TServerTransport serverTransport = new TServerSocket(WhrPublicConstants.RPC_PORT,2000);
TServer server = new TSimpleServer(new Args(serverTransport).processor(processor));
System.out.println("Starting the rpc server... on port:"+WhrPublicConstants.RPC_PORT);
server.serve();
} catch (Exception e) {
e.printStackTrace();
}
}
The rpc method is:
#Override
public int emulateDevice( String msg) throws TException {
throw new RuntimeException("just test throw exception");
return 0;
}
In the client side,I can get the error:
org.apache.thrift.transport.TTransportException
But in the thrift server side, I can't catch the exception as above.
Who can help me? Thanks.

Threaded Server stuck on accept() AKA How to shutdown a MulThreaded Server via client input?

Since I am stuck for this for a week now and still haven't firgured it out I try to express what I want as cleary as possible.
I have a Server which can handle Multiple Clients and communicates with them.
Whenever a client connects, the server passes the Client's request to my class RequestHandler, in which the clients commands are being processed.
If one of the clients says "SHUTDOWN", the server is supposed to cut them loose and shut down.
It doesn't work.
If only one client connects to the server, the server seems to be stuck in the accept() call and I do not know how to fix this.
THERE is already one response, but please do not take note of it, it was on a different topic which is outdated
I have two approaches and both don't seem to work.
1)If the client writes "SHUTDOWN", the shutdownFlag is set to true (in hope to exit the while loop)
2)If the client writes "SHUTDOWN", the static method shutdown() is called on the Server, which should shut him down
Below you see the implementation of my Server class, the other two classes involved are Client(all he does is connect to the Socket) and RequestHandler (this class processes the Input and writes it) .
I am 98% sure the problem lies within the Server class.
Below this is an even shorter version of the Server with just the methods without any Console outputs which might help understanding it in case you want to copy the code
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
System.out.println("Waiting for clients");
while (!shutdownFlag) {
System.out.println("shutdown flag ist : " + shutdownFlag);
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
System.out.println("Hallo");
}
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
serverSocket.close();
}
System.out.println("shutting down");
} catch (IOException e) {
System.out
.println("Exception caught when trying to listen on port "
+ PORTNUMBER + " or listening for a connection");
System.out.println(e.getMessage());
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown(){
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
while (!shutdownFlag) {
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
}
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
serverSocket.close();
}
} catch (IOException e) {
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown() {
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If you move the code in main into an instance method on Server (we'll say run here) you can just do new Server().run() inside main. That way you have an instance (this) to work with inside your run method.
Something like this:
class Server {
private boolean shutdownFlag = false; // This can't be static anymore.
public static final Server SERVER = new Server();
public static void main(String[] args) {
SERVER.run();
}
private void run() {
// Here goes everything that used to be inside main...
// Now you have the Server.SERVER instance to use outside the class
// to shut things down or whatever ...
}
}
This pattern isn't actually that great but better would be too long for here. Hopefully this gets you off to a good start.

java.io.EOFException (having problems with closing streams)

Got a simple client/server app only with login/logout implemented. When i press connect it runs perfect, but the problem comes after when trying to disconnect (getting EOFException on client side).
Im almost sure its due to a poor close of the stream. Any hints?
java.io.EOFException
at java.io.DataInputStream.readByte(DataInputStream.java:98)
at java.io.ObjectInputStream.nextTC(ObjectInputStream.java:506)
at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:778)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2006)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1963)
at com.mtm.ClientConnection.disconnect(ClientConnection.java:54)**
Client class:
public class ClientConnection implements Admin{
public ObjectInputStream in;
public static ObjectOutputStream out;
public Socket socket;
public void connect(){
String host = IP;
int port = PORTO;
try {
socket = new Socket (host,port);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
MSG_Login login = new MSG_Login();
login.setID(DeviceId.getId().toString());
send(login);
Object c1 = in.readObject();
if(c1 instanceof MSG_Login){
Thread thread = new ClientThread(this);
thread.start();
}
}
catch (UnknownHostException e) { e.printStackTrace(); }
catch (SocketException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
}
public void disconnect(){
try {
MSG_Logout logout = new MSG_Logout();
logout.setID(DeviceId.getId().toString());
send(logout);
Object c1 = in.readObject();
if(c1 instanceof MSG_Logout){
in.close();
out.close();
socket.close();
}
}
catch (IOException e) { e.printStackTrace(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
}
public static void send(Object obj) {
try {
out.writeObject(obj);
out.flush();
out.reset();
}
catch (IOException e) { e.printStackTrace(); }
}
}
Server (thread) class:
public class Servidor_Thread extends Thread{
public Socket canal;
Servidor serv;
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
private boolean logOff;
public Servidor_Thread(Servidor serv) {
this.serv = serv;
canal = serv.socket;
logOff = false;
}
public void run(){
try {
ois=new ObjectInputStream(canal.getInputStream());
oos=new ObjectOutputStream(canal.getOutputStream());
while(logOff==false){
Object obj=ois.readObject();/** Objecto recebido - Reconstrução **/
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
if(obj instanceof MSG_Login){
serv.id_database.add(((MSG_Login) obj).getID());
serv.getLog().appendConsole("["+dateFormat.format(date)+"]..........User "+((MSG_Login) obj).getID()+" connected.");
enviar(obj);
}
if(obj instanceof MSG_Logout){
serv.id_database.remove(((MSG_Logout) obj).getID());
serv.getLog().appendConsole("["+dateFormat.format(date)+"]..........User "+((MSG_Logout) obj).getID()+" disconnected.");
enviar(obj);
stopThread();
}
}
}
catch (IOException e) { stopThread(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
}
public void stopThread(){
logOff = true;
try {
ois.close();
oos.close();
canal.close();
} catch (IOException e) { e.printStackTrace(); }
}
public void enviar(Object obj) {
try {
oos.writeObject(obj);
oos.flush();
oos.reset();
}
catch (IOException e) { e.printStackTrace(); }
}
}
There is no problem here to answer. The readObject() method throws EOFException at end of stream. This is its normal behaviour. You have to catch it, close the stream you are reading, and exit the reading loop.

Server reply to Client message failing due to closed socket - Java Client-Server example

I'm creating this little client-server program to learn about sockets, and so far, I'm having a bit of trouble. For the purpose of this post, I consolidated the code into a single class. And the code will compile. (So it will show the same errors I get)
When the client connects to the server, the server socket properly creates a socket on the server-side. The Client then successfully sends a message to the server, but when the server tries to send a response to the client, there is an error saying the socket is closed.
Main.java
package main;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Hashtable;
public class Main {
boolean running = true;
public static void main(String[] args){
new Main().start();
}
public void start(){
new Thread(new ConnectionListener()).start(); //Starts Server
try {
connectToServer();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class ConnectionListener implements Runnable{
public void run() {
ServerSocket ss = null;
try {
ss = new ServerSocket(31415);
}catch (BindException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
while(running){
try {
Socket sock = ss.accept();
ServerConnection c = new ServerConnection(sock);
c.start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void connectToServer() throws UnknownHostException, IOException{
//Create Connection to Server
Socket socket = new Socket("localhost",31415);
ClientConnection cc = new ClientConnection(socket);
cc.start();
//Send First Message to Server
Hashtable<Integer, String> htt = new Hashtable<Integer, String>();
htt.put(0,"Hello, This is a Chat Test");
Message m = new Message(Message.Type.CHAT,htt);
cc.sendMessage(m);
}
public class ServerConnection{
Socket sock;
boolean connected = true;
public ServerConnection(Socket sock){
this.sock = sock;
}
public void start() {
new Thread(new RequestListener()).start();
}
private void handleMessage(Message m){
System.out.println("Server : Handle message " + m.type.toString());
}
public void disconnect(){
System.out.println("Disconnect user");
}
public void sendMessage(Message m){
try {
ObjectOutputStream os = new ObjectOutputStream(sock.getOutputStream());
os.writeObject(m);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class RequestListener implements Runnable{
public void run() {
ObjectInputStream is = null;
try {
is = new ObjectInputStream(sock.getInputStream());
while(connected){
try {
Message m = (Message)
is.readObject(); //EOFException
handleMessage(m);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SocketException e){
disconnect();
e.printStackTrace();
break;
}catch (IOException e) {
//e.printStackTrace(); //EOFException Here
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class ClientConnection {
private Socket socket;
private boolean connected = true;
public ClientConnection(Socket socket) {
this.socket = socket;
}
public void start(){
new Thread(new RequestListener()).start();
}
public void sendMessage(Message m){
try {
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
os.writeObject(m);
os.flush();
os.close();
} catch (IOException e) {
System.out.println("Error Sending Message");
e.printStackTrace();
}
}
public void close() throws IOException{
Message m = new Message(Message.Type.DISCONNECT,null);
sendMessage(m);
socket.close();
}
private void handleMessage(Message m){
System.out.println("Client : Handle message " + m.type.toString());
}
class RequestListener implements Runnable{
public void run() {
ObjectInputStream is = null;
try {
System.out.println(socket.isConnected()); //true
System.out.println(socket.isClosed()); //false
InputStream iss = socket.getInputStream();
is = new ObjectInputStream(iss); //socketClosedException
while(connected){
try {
Message m = (Message)is.readObject();
handleMessage(m);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SocketException e){
System.out.println("Server Disconnected");
break;
}catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Message.java
package main;
import java.io.Serializable;
import java.util.Hashtable;
public class Message implements Serializable{
public enum Type{
LOGIN, PM, DISCONNECT, INCORRECT_LP,CORRECT_LP, UPDATE_USERLIST, CHAT, INCORRECT_VERSION
}
public Type type;
Hashtable ht;
public Message(Type type, Hashtable ht){
this.type = type;
this.ht = ht;
}
public Object get(Object o){
return ht.get(o);
}
}
There's nothing 'random' about it.
Closing the input or output stream of a Socket closes the other stream and the Socket.
In this case you are closing the ObjectOutputStream you have wrapped around the socket's output stream, which closes that output stream, which closes the socket's input stream and the socket.

Maintain server after socket killing

So I have this simple server. What I want to do is keep the server running and waiting for another client, when I kill the clients socket (telnet -> end process).
private ServerSocket serv;
public Server() throws IOException {
try {
serv = new ServerSocket(port);
serv.setReuseAddress(true);
while(true) {
Socket sock = serv.accept();
try {
BufferedReader netIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter netOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
while(true) {
//do stuff
}
} finally {
sock.close();
}
}
} catch (SocketException e) {
recreateSocket();
} catch (IOException e) {
e.printStackTrace();
}
}
private void recreateSocket() {
try {
ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port);
serv = socket;
} catch (IOException e) {
e.printStackTrace();
}
}
Atm it throws bindException, how to deal with it.
Add catch statement(s) to before the finally block (but don't call recreateSocket() there )
Update to clarify, something like this:
while(true) {
//do stuff
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
sock.close();
Start a new thread to handle each accepted connection.
The reason is that you are creating a server socket again. You don't need to do this (the previous one is still working which is why you get a bind exception). This is what you want to do:
private ServerSocket serv;
public Server(int port) throws IOException
{
try {
serv = new ServerSocket(port);
serv.setReuseAddress(true);
while(true) {
Socket sock = serv.accept();
try {
BufferedReader netIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter netOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
// do stuff
} catch(SocketException e) {
e.printStackTrace();
} finally {
sock.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

Categories