如题所示,我想实现在客户端输入的内容显示在服务端上,很简单的一个socket实例,可服务器端总是显示不出来,大家帮我看看问题出在哪?
服务器端代码:
- Java code
import java.net.*;import java.io.*;public class Server { private ServerSocket ss; private Socket socket; private BufferedReader in; private PrintWriter out; public Server() { try { ss = new ServerSocket(10000); while (true) { socket = ss.accept(); in = new BufferedReader(new InputStreamReader(socket .getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); String line = in.readLine(); out.println("you input is :" + line); out.close(); in.close(); socket.close(); ss.close(); } } catch (IOException e) { } } public static void main(String[] args) { new Server(); }}
客户端代码:
- Java code
import java.io.*;import java.net.*;public class Client { Socket socket; BufferedReader in; PrintWriter out; public Client() { try { socket = new Socket("127.0.0.1", 10000); in = new BufferedReader(new InputStreamReader(socket .getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); BufferedReader line = new BufferedReader(new InputStreamReader( System.in)); out.println(line.readLine()); line.close(); out.close(); in.close(); socket.close(); } catch (IOException e) { } } public static void main(String[] args) { new Client(); }}
------解决方案--------------------
首先声明 本人新手
如有错误 概不负责
public class Server {
private ServerSocket ss;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Server() {
try {
ss = new ServerSocket(10000);
while (true) {
socket = ss.accept();
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
String line = in.readLine();
//out.println("you input is :" + line);//你又写入输出流,当然不显示
System.out.println("you input is :" + line);
out.close();
in.close();
socket.close();
ss.close();
}
} catch (IOException e) {
}
}
public static void main(String[] args) {
new Server();
}
}
------解决方案--------------------
服务器端代码:
- Java code
import java.net.*;import java.io.*;public class Server { private ServerSocket ss; private Socket socket; private BufferedReader in; private PrintWriter out; public Server() { try { ss = new ServerSocket(10000); while (true) { socket = ss.accept(); in = new BufferedReader(new InputStreamReader(socket .getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); String line_ = in.readLine(); System.out.println (line_) ; //这里添加此代码 out.println("you input is :" + line_); out.close(); in.close(); socket.close(); ss.close(); } } catch (IOException e) { } } public static void main(String[] args) { new Server(); }}