我使用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*/}}
}
}
答案 0 :(得分:0)
1 /在java中,当你通过java youclass_or_jar_file argument argument
然后,参数[0]将是您输入的第一个参数,而不是 C / C ++ 中的程序名称。因此在这种情况下,您可以使用格式为的参数向量
[host, port, "message"]
。
然后在您的计划中,您只需发送arg[2]
message
2 /要评估收到的表达式,您应该自己实施评估方法。
在这种方法中,我认为您应该将输入解析为postfix notation
http://en.wikipedia.org/wiki/Reverse_Polish_notation,使用堆栈,阅读Wiki以获取更多信息,然后对其进行评估。< / p>
希望这个帮助