我有一个具有TCP Server的Java应用程序,它可以处理客户端请求。现在,我想创建一个TCP备份服务器,以便在TCP服务器出现故障时,备份服务器从TCP服务器发生故障的那一刻继续并处理客户端请求。
这怎么办?
我有一个客户端和一个服务器。
这是我现在的TCP Server代码。
import java.net.*;
import java.io.*;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class TCPServer {
static ScriptEngineManager mgr;
static ScriptEngine engine;
public static void main(String args[]) {
mgr = new ScriptEngineManager();
engine = mgr.getEngineByName("js");
try {
int serverPort = 7896; // the server port
ServerSocket listenSocket = new ServerSocket(serverPort);
while (true) {
System.out.println("Server is ready and waiting for requests .... ");
Socket clientSocket = listenSocket.accept();
System.out.println("request received from client with IP : " + clientSocket.getInetAddress());
System.out.println("port of client : " + clientSocket.getPort());
Thread c = new Connection(clientSocket);
}
} catch (IOException e) {
//if already in use then redirect the request to backup server
System.out.println("Listen socket:" + e.getMessage());
}
}
}
class Connection extends Thread {
DataInputStream in;
DataOutputStream out;
Socket clientSocket;
public Connection(Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new DataInputStream(clientSocket.getInputStream());
out = new DataOutputStream(clientSocket.getOutputStream());
this.start();
} catch (IOException e) {
System.out.println("Connection:" + e.getMessage());
}
}
public void run() {
//send client request to bacckup server, with client IP adddress and port number
//BackupTCPServer bus = new BackupTCPServer();
//bus.clientIP = clientSocket.getInetAddress();
//bus.clientPort = clientSocket.getPort();
//System.out.println(bus);
try {
String s = in.readUTF();
//bus.Expressionsbackup.add(s);
String exp = "";
int res = 0;
while (s != null) {
TCPServer.engine.put("i", 2);
TCPServer.engine.put("j", 4);
exp =s;
Object result = TCPServer.engine.eval(exp);
double st = (Double)result;
out.writeUTF(Double.toString(st));
//bus.expressionevaluated++;
s = in.readUTF();
}
}
catch (ScriptException se) {
System.out.println("SE:" + se.getMessage());
}
catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} finally {
try {
clientSocket.close();
} catch (Exception e) {
/*close failed*/
}
}
}
}