我想做一個簡單的回聲客戶端服務器程序。我能夠將客戶端的值發送到服務器並打印出來。但我不能夠從服務器到客戶端獲得的價值回報,這是低於簡單的回聲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在服務器上工作,而服務器執行打印操作,所以沒有新行,客戶端等待它。 –