我正在做套接字编程,有很多客户端连接到服务器,并且服务器必须保持运行,以便任何客户端可以随时连接。我的问题是处理服务器套接字中的异常。如果来自客户端的任何消息未格式化,服务器将抛出异常,在这种情况下,服务器抛出异常并停止。但我需要 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();
}
}
}
}
如何解决这个问题,一旦抛出异常服务器就会停止,如何保持服务器运行?谁能帮我解决这个问题
最佳答案
只需从 catch block 中删除 return 语句
关于java - 在java中处理异常而不导致服务器套接字崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28064356/