Socket 기반 server, client 의 간단 한 인 스 턴 스
1, 서버 일괄 처리 명령 열기:
- :参数1:端口 参数2:Service name
- java -jar EP400ProToolkitServer.jar 5678 GP_CLT_Service
2, 서버 클래스:
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import org.apache.log4j.Logger;
- import org.apache.log4j.PropertyConfigurator;
-
- import com.mmm.ep400.toolkit.ExecuteCMD;
-
- public class RestartServer extends Thread{
- private static Logger logger = Logger.getLogger(RestartServer.class.getName());
- private Socket client;
- private String service;
-
- public RestartServer(Socket c, String service) {
- this.client = c;
- this.service = service;
- logger.info("Accept new client: " + client.getInetAddress().getHostName() + "/" +
- client.getInetAddress().getHostAddress() + ":" + String.valueOf(client.getPort()));
- }
-
- public static void main(String[] args) throws IOException {
- int port = 0;
- String service = null;
- PropertyConfigurator.configure("log4j.properties");
- if (args.length == 2){
- logger.info("Bind port " + args[0]);
- logger.info("Work service " + args[1]);
- if(args[0].matches("[0-9]+")){
- port = Integer.parseInt(args[0]);
- }
- service = args[1].trim();
- }
- if (port < 1024 || port > 65535 || service == null || service.equals("")){
- logger.error("Please init the port between 1024 ~ 65535 and service name");
- System.exit(MAX_PRIORITY);
- }
-
- ServerSocket server = new ServerSocket(port);
- logger.info("Server started");
- while (true) {
- // transfer location change Single User or Multi User
- RestartServer mu = new RestartServer(server.accept(), service);
- mu.start();
- }
- }
-
- public void run() {
- boolean closeServer = false;
- String availableCMD = "available commond: start, stop, restart, exit, clsv (close EP400Pro toolkit service)";
- try {
- BufferedReader in = new BufferedReader(new InputStreamReader(
- client.getInputStream()));
- PrintWriter out = new PrintWriter(client.getOutputStream());
- out.println("Info from server: Connected to EP400Pro toolkit service");
- out.println(availableCMD);
- out.println("--Info End--");
- out.flush();
- // Mutil User but can't parallel
- while (true) {
- String str = in.readLine();
- logger.info(str);
- if (str.toLowerCase().equals("start")) {
- workCommand(out, "net start " + service);
- out.println("--Info End--");
- out.flush();
- }
- else if (str.toLowerCase().equals("stop")) {
- workCommand(out, "net stop " + service);
- out.println("--Info End--");
- out.flush();
- }
- else if (str.toLowerCase().equals("restart")) {
- if (workCommand(out, "net stop " + service)) {
- workCommand(out, "net start " + service);
- }
- out.println("--Info End--");
- out.flush();
- }
- else if (str.toLowerCase().equals("exit")) {
- break;
- }
- else if (str.toLowerCase().equals("clsv")) {
- closeServer = true;
- out.println("Info from server: EP400Pro toolkit service is to be closed");
- logger.info("EP400Pro toolkit service is to be closed");
- break;
- }
- else {
- out.println("Info from server: Error commond
" + availableCMD);
- logger.info("Error commond
" + availableCMD);
- out.println("--Info End--");
- out.flush();
- }
- }
- out.println("Info from server: Disconnected to EP400Pro toolkit service");
- out.println("--Info End--");
- out.flush();
- client.close();
- logger.info("Closed client: " + client.getInetAddress().getHostName() + "/" +
- client.getInetAddress().getCanonicalHostName() + ":" + String.valueOf(client.getPort()));
- if (closeServer){
- logger.info("Close myself");
- System.exit(MAX_PRIORITY);
- }
- } catch (IOException e) {
- logger.error(e.getMessage());
- } finally {
- if (!client.isClosed()){
- try {
- client.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- logger.error(e.getMessage());
- }
- }
- }
- }
-
- private boolean workCommand(PrintWriter out, String cmd){
- if (ExecuteCMD.invokeOuterApplication(cmd)) {
- out.println("Info from server: Execute \"" + cmd + "\" successfully");
- logger.info("Execute \"" + cmd + "\" successfully");
- return true;
- }
- else {
- out.println("Info from server: Execute \"" + cmd + "\" failed");
- logger.error("Execute \"" + cmd + "\" failed");
- return false;
- }
- }
- }
3, 클 라 이언 트 일괄 처리 명령:
- :参数1: server 参数2: port 参数3: command
- :command:
- :start: 启动服务
- :stop: 关闭服务
- :restart:重启服务
- :exit:退出本程序
- :clsv:关闭EP400Pro Toolkit Service
- :line:进入命令行模式
- java -jar EP400ProToolkitClient.jar 127.0.0.1 5678 line
- pause
4, 클 라 이언 트 클래스
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- //import java.net.InetAddress;
- import java.net.Socket;
-
- import org.apache.log4j.Logger;
- import org.apache.log4j.PropertyConfigurator;
-
- public class RestartClient {
- private static Logger logger = Logger.getLogger(RestartClient.class.getName());
- static Socket server;
-
- public static void main(String[] args) throws Exception {
- String serverStr = null;
- String para = null;
- int port = 0;
- PropertyConfigurator.configure("log4j.properties");
- if (args.length == 3){
- logger.info("Server " + args[0]);
- logger.info("Server port " + args[1]);
- logger.info("Command " + args[2]);
- serverStr = args[0].trim().toLowerCase();
- if(args[1].matches("[0-9]+")){
- port = Integer.parseInt(args[1].trim());
- }
- para = args[2].trim().toLowerCase();
- }
- if (serverStr == null || serverStr.equals("") ||
- para == null || para.equals("") ||
- port < 1024 || port > 65535){
- logger.warn("Please init parameters: server port (1024~65535) command");
- System.exit(0);
- }
- //server = new Socket(InetAddress.getLocalHost(), 5678);
- server = new Socket(serverStr, port);
- BufferedReader in = new BufferedReader(new InputStreamReader(
- server.getInputStream()));
- PrintWriter out = new PrintWriter(server.getOutputStream());
- BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
-
- String serverResponse = in.readLine();
- while (serverResponse != null){
- //Server端如果不发结束符,则一直等待在in.readline(); 我想也可以用线程来专门处理输入输出,但我没有试过。
- if (serverResponse.equals("--Info End--")){
- break;
- }
- logger.info(serverResponse);
- serverResponse = in.readLine();
- }
-
- boolean byLine = para.equals("line");
- String str = null;
- while (true) {
- str = (byLine ? wt.readLine() : (str == null ? args[2] : str));
- out.println(str);
- out.flush();
- logger.info("Commond \"" + str + "\" is sent to server");
- serverResponse = in.readLine();
- while (serverResponse != null){
- if (serverResponse.equals("--Info End--")){
- break;
- }
- logger.info(serverResponse);
- serverResponse = in.readLine();
- }
- if (str.toLowerCase().equals("exit") || str.toLowerCase().equals("clsv")) {
- break;
- }
- if (!byLine){
- str = "exit";
- }
- }
- logger.info("Exit successfully");
- server.close();
- }
- }
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.