簡體   English   中英

JAVA中的客戶端/服務器表達式評估

[英]Client/server expression evaluation in JAVA

我已經使用TCP創建了一個簡單的客戶端服務器應用程序。 我正在使用eclipse,並且對TCP來說是個新手,所以我的問題是:1)如果我希望客戶端發送諸如“ 10 + 20-5”的表達式,那么我將其放在參數中? 這是arg [0]。 2)發送完上述表達式后,如何使服務器計算該實際表達式,以便將結果“ 25”返回給客戶端?

客戶代碼:

public class TCPClient {
public static void main (String args[]) { 
   // arguments supply message and hostname
    Socket s = null;
    try{
        int serverPort = 7896;
        s = new Socket(args[1],serverPort);

        DataInputStream in =new DataInputStream(s.getInputStream());
        DataOutputStream out = new DataOutputStream(s.getOutputStream());

        out.writeUTF(args[0]);
        String data = in.readUTF(); 
        System.out.println("Received: "+ data) ;
        }catch (UnknownHostException e) {System.out.println("Socket:"+e.getMessage());
        }catch (EOFException e){System.out.println("EOF:"+e.getMessage());
        }catch (IOException e){System.out.println("readline:"+e.getMessage());
        }finally {if(s!=null) 
        try {s.close(); 
        }catch (IOException e) {System.out.println ("close:" + e.getMessage());}
    }
}

}

服務器代碼:

public class TCPServer {
public static void main (String args[]) {
    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();
            Connection c = new Connection(clientSocket);

        }
        } catch(IOException e) {System.out.println("Listensocket:"+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(){
        try {   
            String data = in.readUTF();  
            out.writeUTF(data);
        }catch (EOFException e){System.out.println("EOF:"+e.getMessage());
        } catch(IOException e) {System.out.println("readline:"+e.getMessage());
        } finally{ try {clientSocket.close();}catch (IOException e){/*close failed*/}}
}
}

1 /在Java中,當您傳遞java youclass_or_jar_file argument argument時,您會使用java youclass_or_jar_file argument argument

然后,參數[0]將是您輸入的第一個參數 ,而不是C / C ++中的程序名稱。 因此,在這種情況下,您可以使用格式為[host, port, "message"]的參數向量。 然后,在您的程序中,您只需發送arg[2]在這種情況下就是message

2 /要評估接收到的表達式,您應該自己實現評估方法。

在我看來,以這種方法,您應該使用stack將輸入解析為postfix notation http://en.wikipedia.org/wiki/Reverse_Polish_notation ,閱讀Wiki以獲得更多信息,然后對其進行評估。

希望這個幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM