标签:步骤 刷新 服务端 put readline server main dmi 服务
public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("服务器启动中...."); //accept()是在一个套接口接受的一个连接。accept()是c语言中网络编程的重要的函数, //本函数从s的等待连接队列中抽取第一个连接,创建一个与s同类的新的套接口并返回句柄。 Socket socket = serverSocket.accept();//获取Socket InputStream is = socket.getInputStream();//获取输入流 InputStreamReader isr = new InputStreamReader(is);//InputStreamReader类是从字节流到字符流的桥接器 BufferedReader br = new BufferedReader(isr);//缓冲流 System.out.println("客户端数据" + br.readLine()); String info = null; while((info = br.readLine()) != null){ System.out.println("客户端传递的信息" + info); } socket.shutdownInput();//shutdownInput和shutdownOutput只关闭相应的输入、输出流,不会同时关闭网络连接的功能。 OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("欢迎您!!"); pw.flush();//flush()是清空,而不是刷新 将缓冲区的内容输出 pw.close(); os.close(); br.close(); isr.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
public class Client { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 8888); System.out.println("客户端启动中...."); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); pw.write("admin"); pw.flush(); socket.shutdownOutput(); InputStream is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String info = null; while((info = br.readLine()) != null){ System.out.println("服务端返回的信息" + info); } os.close(); pw.close(); is.close(); br.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } }
标签:步骤 刷新 服务端 put readline server main dmi 服务
原文地址:https://www.cnblogs.com/ch94/p/10155590.html