所以我用java为我的大学迷你项目做了这个客户端服务器程序。请注意,这只是我正在处理的一个大项目的一个小模块。我需要一个字符串从客户端发送到服务器。服务器将返回字符串,因为它返回给客户端。(稍后将修改代码,以便在发送回之前处理字符串)。客户端将在需要时向服务器发送一个字符串。因此,这意味着服务器必须无限期地运行。
我在这里面临的问题是,我的服务器仅在客户端发送字符串时才第一次完美运行。如果我第二次使用不同的字符串运行客户端,我会返回之前发送到服务器的相同字符串!
这是我的服务器程序:
public class Server {
public static boolean x = true;
public static String reply;
public static void main(String a[]) throws Exception {
System.out.println("Entered server console..");
Socket echoSocket = null;
ServerSocket serverSocket = null;
PrintWriter out = null;
BufferedReader in = null;
System.out.println("Initializing Connection..");
boolean runFlag = true;
try {
serverSocket = new ServerSocket(77);
while (runFlag) {
echoSocket = serverSocket.accept();
out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
while (x) {
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
reply = in.readLine();
if (reply != null) {
x = false;
}
}
System.out.println("received: " + reply);
out.println(reply);
System.out.println("sent back: " + reply);
stdIn.close();
}
} catch (Exception e) {
System.out.println("Exception in starting server: " + e.getMessage());
} finally {
out.close();
in.close();
echoSocket.close();
}
}
}
这是我的客户程序:
public class Client {
public static String reply,temp;
public static boolean x=true;
public Client()
{
temp="lala";
}
public Client(String t)
{
temp=t;
}
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 77);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
temp="lala"; //this is the string to be sent
out.println(temp);
while (x) {
reply= in.readLine();
if(reply!=null)
{
x=false;
}
}
System.out.println("reply: "+reply);
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
谁能帮我找出这里的问题?