遇见花开遇见你啊
2017-02-06 14:21
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class ServerSocketTest { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("============服务器即将启动,等待客户端的链接请求==============="); Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String buffer = br.readLine(); while (buffer != null) { System.out.println("我是服务器端,客户端向我发送信息为: " + buffer); } socket.shutdownInput(); br.close(); isr.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.unit02; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class ClientTest { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 8888); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("用户名: admin; 密码: 123"); pw.flush(); socket.shutdownOutput(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
String buffer = br.readLine();
while (buffer != null) {
System.out.println("我是服务器端,客户端向我发送信息为: " + buffer);
}
这句话有问题了,buffer在读取玩br.readLine(),的时候就是已经有数值了,你在循环的时候已经进入了while(1)z这样的情况,他是不会跳出循环的,所以一直在重复打印
String buffer=br.readLine(); while(br.readline()!=null){ buffer=br.readLine(); System.out.println("我是服务器端,客户端向我发送信息为: " + buffer);
Java Socket应用---通信是这样练成的
125013 学习 · 590 问题
相似问题