next()从遇到第一个有效字符(非空格、换行符)开始扫描,遇到第一个分隔符或结束符(空格’ ‘或者换行符 ‘\n’)时结束。 nextLine()则是扫描剩下的所有字符串知道遇到回车为止。
java 怎么让打印信息换行? System.out.println(“账号==”+name+"\n"); System.out.println(“密码==”+pwd+"\n");
服务端 public static void main(String[] args) {
Scanner sc = new Scanner(System.in); try{ ServerSocket server=new ServerSocket(8880); // 定义一个服务器,定义端口 if(server !=null){ System.out.println("创建服务端成功"); } //建立socket接口,accept方法是一个阻塞进程,等到有用户连接才往下走 // 定义Socket类 Socket lianjie = server.accept(); System.out.println("有客户端接入"); //获取输入通道,用来读取数据 InputStream in=lianjie.getInputStream(); byte[]mes=new byte [128]; int len; len=in.read(mes); System.out.println(new String(mes,0,len)); System.out.println("服务端接收数据完毕"); System.out.println("请输入要发送给客户端的消息:"); String str = sc.nextLine(); OutputStream out = lianjie.getOutputStream(); // 向客户端发送消息 out.write(str.getBytes()); //byte[]解析成字符串。 System.out.println("服务器发送数据完毕"); //关闭 否则关闭时会有错误 in.close(); out.close(); lianjie.close(); server.close(); }catch(Exception e){ System.out.println("创建失败"); e.printStackTrace(); }} 客户端 public static void main(String[] args) {
Scanner sc=new Scanner(System.in); //System.in作为InputStream类的对象实现标准输入, //可以调用它的read方法来读取键盘数据。read方法如下:int read() String mes; try{ Socket client =new Socket("192.168.175.1", 8880); //127.0.01任何时候都代表本机IP地址,8880是自定义的端口号 //Socket(String host, int prot); //主要使用 OutputStream out =client.getOutputStream(); // 向客户端发送消息 //将byte[]mes =new byte[128] System.out.print("请输入发送的数据"); mes =sc.nextLine(); //从键盘获取输入 out.write(mes.getBytes()); //byte[]解析成字符串。 //c字符串是数组,java的字符串是类,数组书数组 System.out.print("客户端发送完毕"+mes+"\n"); InputStream in = client.getInputStream(); int len; byte[] readMes = new byte[128]; len = in.read(readMes); System.out.println("len="+len+"\n"); if(len != -1){ System.out.println("读到数据:"+new String(readMes,0,len)); }else{ System.out.println("数据错误"); } out.close(); in.close(); client.close(); }catch (Exception e){ e.printStackTrace(); }