我正在尝试编写在线出租车服务程序。我需要向服务器发送多个命令,并以字符串形式接收每次旅行过程的响应,但是我只能执行一次,然后我的程序什么也不做。我该怎么办? 这是我的服务器代码
Runnable passengerR = new Runnable() {
private ArrayList<String> tokens;
@Override
public void run() {
Socket passengerSocket;
try {
ServerSocket serverSocketPassenger = new ServerSocket(5050);
while(true) {
passengerSocket = serverSocketPassenger.accept();
InputStream inputStream = passengerSocket.getInputStream();
OutputStream outputstream = passengerSocket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while(true) {
String Line = reader.readLine();
System.out.println(Line);
while(Line!= null) {
ServerWorker worker = new ServerWorker(Line);
this.tokens = worker.token();
if(tokens.get(0).equals("request")) {
worker.handelRequest();
worker.send("waiting", passengerSocket);
}
if(tokens.get(0).equals("cancel")) {
worker.send("cancel", passengerSocket);
}
if(tokens.get(0)=="payment") {
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
这是我的客户代码
public class PassengerClient extends Thread {
public static String command="A";
private String opratingcommand="B";
@Override
public void run() {
try {
Socket socket2 = new Socket("127.0.0.1", 5050);
System.out.println("Passenger Successfuly connected to: "+ socket2.getInetAddress());
//client to server
while(true) {
if(!opratingcommand.equals(command)) {
while(true) {
PassengerClient.command = PassengerView.commandp;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(command != null) {
System.out.println(command);
opratingcommand = command;
command = null;
break;
}
}
PrintWriter printWriter = new PrintWriter(socket2.getOutputStream());
printWriter.println(opratingcommand);
printWriter.flush();
System.out.println("CLIENT SIDE: Message Sent -> "+opratingcommand);
}
//server to client
InputStream inputStream = socket2.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line=reader.readLine();
while(line != null) {
System.out.println(line);
line = null;
}
line=reader.readLine();
if(line.equals("cancel")) {
System.out.println("travel canceled");
}
if(line.equals("quit")) {
socket2.close();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}