public class Server { 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 info = null; while ((info=br.readLine())!=null) { System.out.println("我是服务器,客户端说" + info); } br.close(); isr.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public class Client { 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) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
原文:https://www.cnblogs.com/dulute/p/10824723.html