public class Server2 { public static void main(String[] args) throws Exception { System.out.println("==服务器的启动=="); // 1.注册端口 ServerSocket serverSocket = new ServerSocket(8888); while (true) { //2.每接收到客户端的连接,就新建一个线程进行处理 Socket socket = serverSocket.accept(); new ServerReadThread(socket).start(); System.out.println(socket.getRemoteSocketAddress() + "上线!"); } } static class ServerReadThread extends Thread { private Socket socket; public ServerReadThread(Socket socket) { this.socket = socket; } @Override public void run() { BufferedWriter writer=null; BufferedReader reader=null; try { writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); //4.把字节输入流包装成自己需要的流进行数据的读取。 reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); //5.循环读取数据并打印到屏幕 String line; while ((line = reader.readLine()) != null) { System.out.println("收到:" + line); writer.write("hello,"+line+"\n"); } } catch (IOException e) { System.out.println(socket.getRemoteSocketAddress() + "下线!"); }finally { try { writer.close(); reader.close(); socket.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } } } }
public class Client2 { public static void main(String[] args) { Socket socket = null; BufferedReader reader = null; BufferedWriter writer = null; BufferedReader consoleReader = null; try { socket=new Socket("127.0.0.1",8888); reader=new BufferedReader(new InputStreamReader(socket.getInputStream())); writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); consoleReader=new BufferedReader(new InputStreamReader(System.in)); while (true){ String line = consoleReader.readLine(); writer.write(line+"\n"); writer.flush(); String msg= reader.readLine(); System.out.println(msg); if(line.equalsIgnoreCase("quit")){ break; } } } catch (IOException e) { System.err.println(e); }finally { try { writer.close(); socket.close(); System.out.println("关闭socket"); reader.close(); consoleReader.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } } }
标签:writer,java,socket,编程,System,测试,reader,println,new From: https://www.cnblogs.com/wangbin2188/p/17165305.html