处理异常而不会破坏Java中的Server Socket?

时间:2015-01-21 10:04:16

标签: java sockets serversocket

我正在进行Socket编程,因为许多客户端连接到服务器,并且服务器必须继续运行,以便任何客户端都可以随时连接。我的问题是在服务器套接字中处理异常。如果从客户端传入的任何msg未格式化,则服务器将抛出异常,在这种情况下,服务器将抛出异常并停止。但是我需要Server shd继续运行。如何解决这个问题,

这是我的服务器代码,

 public class SimpleServer extends Thread {
 private ServerSocket serverSocket = null;
 private Socket s1=null;
 InputStream s1In=null;
 DataInputStream dis=null;
 OutputStream out=null;
 DataOutputStream dos=null;
 SimpleServer()
    {
        try {
            serverSocket = new ServerSocket(1231);
            this.start();
        } catch (IOException ex) {
             System.out.println("Exception on new ServerSocket: " + ex);
        }
    }

  public void run()
    {


        while(true){
            try {

                 System.out.println("Waiting for connect to client");
                 s1=serverSocket.accept();


                 s1In = s1.getInputStream();
                 dis = new DataInputStream(s1In);

                 out=s1.getOutputStream();
                 dos=new DataOutputStream(out);

                 String clientData=dis.readUTF();
                 System.out.println(clientData);

                 String[] data=clientData.split("#");

                 String msg_type =data[0];
                 String busId=data[1];  // Here it may throw ArrayIndexoutofBoundException

               //My other codding Stuff
                 dos.writeUTF("Bus Registered Successfully");
                 dos.flush();
                 s1.close();


              }
              catch (IOException ex) {

                System.out.println("Exception in while " +ex.getMessage());
                try {
                    s1.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                //ex.printStackTrace();
            }
            catch (Exception e) {
                System.out.println("Exception is: "+e);
                try {
                    s1.close();
                } catch (IOException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
            }

      }

 }

如何解决此问题,一旦它抛出异常,服务器将停止,如何保持服务器运行?请允许任何人帮助我

2 个答案:

答案 0 :(得分:0)

只需从catch块中删除return语句

答案 1 :(得分:0)

您需要在单独的线程中处理与客户端的每个接受的连接。使用java 7 ExecutorService和一些java 8 lambda代码,它看起来像这样:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleServer {
    private final ExecutorService executorService;

    SimpleServer() {
        this.executorService = Executors.newFixedThreadPool(10);
        try (ServerSocket serverSocket = new ServerSocket(1231)) {
            while (true) {
                System.out.println("Waiting for connect to client");
                Socket socket = serverSocket.accept();
                new ConnectionHandler(socket).startInThread();
            }
        } catch (IOException ex) {
            System.out.println("Exception on new ServerSocket: " + ex);
        }
    }

    private class ConnectionHandler {
        private final Socket socket;

        private ConnectionHandler(Socket socket) {
            this.socket = socket;
        }

        private void handle() {
            try {
                InputStream s1In = socket.getInputStream();
                DataInputStream dis = new DataInputStream(s1In);

                OutputStream out = socket.getOutputStream();
                DataOutputStream dos = new DataOutputStream(out);

                String clientData = dis.readUTF();
                System.out.println(clientData);

                String[] data = clientData.split("#");

                String msg_type = data[0];
                String busId = data[1];

                dos.writeUTF("Bus Registered Successfully");
                dos.flush();
            } catch (Exception ex) {
                System.err.print("Exception: ");
                ex.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.err.print("Exception on socket.close()");
                    e.printStackTrace();
                }
            }
        }

        private void startInThread() {
            executorService.execute(this::handle);
        }
    }
}