我正在尝试制作一个简单的echo客户端服务器程序。我能够将值从客户端发送到服务器并打印出来。但我无法从服务器到客户端获取值这是下面的代码
客户端代码
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);
}
}
}
提前谢谢。
答案 0 :(得分:0)
您在服务器代码中的确切位置是否正在尝试写入客户端?您是否尝试在服务器控制台上编写并期望它出现在客户端控制台上?然后你需要产生一个线程并与它共享输出流对象,以便直接回到客户端。如果您只想回显客户端在控制台中键入的字符串,请添加os.write(r.getBytes());和os.flush();在你的while循环的底部。