【网络编程】java利用Socket在控制台互发信息。但是在客户端控制台输入信息后,服务器端控制台无消息显示。
原因:PrintWriter printWriter = new PrintWriter(outputStream, true);
必须在加上true,意味着想要将数据打印到outputStream中,并使用自动刷新。
加上后代码如下,结果如图:
客户端:
1 | public class Client3 { |
服务器端:
1 | package server; |
也可以利用多线程实现上述代码。只需要改变Server3.java,再增加一个ServerThread.java即可。
Server3.java
public class Server3 {
public static void main(String[] args) throws IOException {
// 服务端需要使用serversocket来开放本地的端口
ServerSocket serverSocket = new ServerSocket(10001);
Socket socket = serverSocket.accept();
ServerThread serverThread = new ServerThread(socket);
new Thread(serverThread).start();
}
}
ServerThread.java
public class ServerThread implements Runnable{
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
//------------接收客户端数据---------------
// 通过server获取输入流对象
InputStream inputStream = null;
inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(inputStreamReader);
//------------向客户端输出数据---------------
OutputStream outputStream = null;
outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream, true);
InputStreamReader isr2 = new InputStreamReader(System.in);
BufferedReader br2 = new BufferedReader(isr2);
while (true) {
String str = null; //读出缓存区数据
str = br.readLine();
System.out.println("客户端说:" + str);
System.out.println("我说:");
String str2 = null;
str2 = br2.readLine();
printWriter.println(str2);
}
} catch (Exception e){
}
}
}