Day20 Java网络编程

java如何实现的网络通信

1.使用IP地址---定位一台主机 使用端口号---定位一个应用 ===>InetAddress类

创建一个InetAddress的对象InetAddress inet = InetAddress.getByName("www.baidu.com");
获取本机的一个InetAddress的对象 getLocalHost()
域名:getHostName() ip:getHostAddress()

    public static void client() throws IOException{
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
    
    OutputStream os = socket.getOutputStream();
    
    System.out.println("请输入多个字符:");
    
    Scanner scanner = new Scanner(System.in);
    String str = scanner.next();
    
    os.write(str.getBytes());
    
    socket.shutdownOutput();
    
    InputStream is = socket.getInputStream();
    
    byte[] b = new byte[10];
    int len;
    
    while((len = is.read(b)) != -1){
        System.out.print(new String(b, 0 , len));
    }
    
    is.close();
    scanner.close();
    os.close();
    socket.close();
    
}


public static void server() throws IOException{
    ServerSocket ss = new ServerSocket(9090);
    
    Socket socket = ss.accept();
    
    InputStream is = socket.getInputStream();
    
    InputStreamReader isr = new InputStreamReader(is);
    
    char[] c = new char[20];
    int len;
    StringBuffer sb = new StringBuffer() ;
    
    while((len=isr.read(c))!=-1){
        sb.append(c, 0, len);
    }
    
    String restr = sb.toString().toUpperCase();
    
    OutputStream os = socket.getOutputStream();
    
    os.write(restr.getBytes());
    
    os.close();
    isr.close();
    socket.close();
    ss.close();
    
    
}

推荐阅读更多精彩内容