我想做一个简单的回声客户端服务器程序。我能够将客户端的值发送到服务器并打印出来。但我不能够从服务器到客户端获得的价值回报,这是低于简单的回声java客户端服务器程序
客户端代码
public class Client_1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
System.out.println("client signing on");
Socket soc = new Socket("127.0.0.1", 5556);
t t = new t(soc);
Thread t1 = new Thread(t);
t1.start();
OutputStream os = soc.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw, true);
InputStream is = System.in;
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
while (!s.equals("end")) {
// System.out.println(s);
pw.println(s);
s = br.readLine();
}
pw.println("end");
System.out.println("client signing off");
}
代码}
class t implements Runnable {
static Socket soc;
static String read;
public t(Socket soc) {
this.soc = soc;
}
@Override
public void run() {
try {
System.out.println("conn established");
InputStream is = soc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
while (!s.equals("end")) {
System.out.println(s);
s = br.readLine();
}
} catch (IOException ex) {
}
}
}
服务器代码
public class server {
static Socket soc;
static String r;
static BufferedReader br;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
System.out.println("server signing on");
ServerSocket ss = new ServerSocket(5556);
soc = ss.accept();
InputStream is = soc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
OutputStream os;
os = soc.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw,true);
br = new BufferedReader(isr);
r = br.readLine();
while (!r.equals("end")) {
System.out.println(r);
// PrintWriter out = new PrintWriter(new FileWriter("c:\\outputfile.txt"));
pw.print("test");
pw.print(r);
r = br.readLine();
}pw.print("end");
System.out.println("server signing off");
} catch (Exception e) {
System.out.println(e);
}
}
}
预先感谢您。
客户端执行println操作,所以readLine在服务器上工作,而服务器执行打印操作,所以没有新行,客户端等待它。 –