java 网络编程

IP:用来定位一台计算机。


      ip地址的分类:

IP地址分类:

  1. ipv4:4个字节组成,每个字节0~255。
  2. ipv6:8个无符号整数组成。

公网(互联网),私网(局域网):

  1. ABCD地址
  2. 192.168.xx.xx,专门给组织内部使用

下面是对IP创建和常用方法:


端口:计算机上的一个程序的进程。

端口的分类:

                公有端口(0~1023):

                        HTTP:80;    HTTPS:443;  FTP:21;   Telent:23。

                程序注册端口(1024~4915):

                        Tomcat:8080;   MySQL:3306;    Oracle:1521。

                动态,私有端口(49152~65535)。


如下是端口的创建和常用方法:

public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress socketAddress=new InetSocketAddress("127.0.0.1",8080);
        InetSocketAddress socketAddress1=new InetSocketAddress("localhost",8080);
        System.out.println(socketAddress);
        System.out.println(socketAddress1);
        System.out.println(socketAddress.getAddress());     //地址
        System.out.println(socketAddress.getHostName());    //地址
        System.out.println(socketAddress.getPort());       //端口
    }
}

    


通信协议:计算机沟通的某种约定。

                TCP:用户传输协议。

                 UDP:用户数据报协议。

                 IP:网络互联协议。


TCP的通信:(IP,port)

        客户端:

  1. 连接服务器 Socket
  2. 发送信息

        服务器:

  1. 建立服务器的端口 ServerScoker
  2. 等待用户的连接 accept
  3. 接收用户的消息

    如下是TCP通信的小例,实现了客户端发消息,服务端接收:

客户端

public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.要知道服务器的地址,端口号
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 999;
            //2.创建一个socket连接
            socket = new Socket(serverIP, port);
            //3.发送消息
            os = socket.getOutputStream();
            os.write("Hello World,Hello Time".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

服务端

public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;
        try{
            //1地址
        serverSocket = new ServerSocket(999);
        while(true){
            //2.等待客户端连接
            socket=serverSocket.accept();
            //3.读取客户端信息
            is=socket.getInputStream();
            //管道流
            baos=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len;
            while((len=is.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
        }

    } catch(IOException e) {
        e.printStackTrace();
    }finally {
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
          if(is!=null){
              try {
                  is.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
           if(socket!=null){
               try {
                   socket.close();
               } catch (IOException e) {
                   throw new RuntimeException(e);
               }
           }
           if(serverSocket!=null){
               try {
                   serverSocket.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }


        }
}

}

TCP传输文件:

服务端

class TcpServerDemo2 {
    public static void main(String[] args) throws IOException {
        //1.创建服务
        ServerSocket serversocket=new ServerSocket(9000);
        //2.监听客户端的连接
        Socket socket=serversocket.accept();  //阻塞式监听,会一直等待客户端连接
        //3.获取输入流
        InputStream is=socket.getInputStream();
        //4.文件输出
       FileOutputStream fos=new FileOutputStream(new File("revceive.jpg"));
       byte[] buffer=new byte[1024];
       int len;
       while ((len=is.read(buffer))!=-1){
           fos.write(buffer,0,len);
       }
       //关闭资源
        fos.close();
       is.close();
       socket.close();
       serversocket.close();
    }
}

客户端

public class TcpClinetDemo2 {
    public static void main(String[] args) throws Exception {
        //1.创建一个Socket连接
        Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9000);
//        2.创建一个输出流
        OutputStream os=socket.getOutputStream();
//        3.文件流
        FileInputStream fis=new FileInputStream(new File("hl.jpg"));
        //4.写出文件
        byte[] buffer=new byte[1024];
        int len;
        while((len=fis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }
        //5.关闭资源
        fis.close();
        os.close();
        socket.close();
    }
}

UDP通信:不需要连接,需要知道对方的地址

客户端

public class UDPClientDemo1 {
    public static void main(String[] args) throws IOException {
        //1.创建一个Socket
        DatagramSocket socket=new DatagramSocket();
        //2.创建一个包
        String msg="你好!";
        InetAddress localhost=InetAddress.getByName("localhost");
        int port=9090;
        //数据,数据长度,发送对象
        DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.length(),localhost,port);
        //3.发送包
        socket.send(packet);
        //4.关闭流
        socket.close();
    }
}

服务端

public class UDPServerDemo1 {
    public static void main(String[] args) throws IOException {
        //开发端口
        DatagramSocket socket=new DatagramSocket(9090);
        //接受数据
        byte[] buffer=new byte[1024];
        DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);
        socket.receive(packet);//阻塞接收
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        //关闭连接
        socket.close();
    }
}

UDP聊天:

发送者

public class UDPSenderDemo1 {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8888);
        //准备数据,从控制台读取
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String data = reader.readLine();
            byte[] datas = data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
            socket.send(packet);
            if (data.equals("再见")){
                break;
            }
        }

        socket.close();
    }
}

接收者

public class UDPReceiverDemo1 {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket=new DatagramSocket(6666);
      while(true){
          //接收包
          byte[] container=new byte[1024];
          DatagramPacket packet=new DatagramPacket(container,0,container.length);
          socket.receive(packet);//阻塞式连接包裹
          //断开连接
          byte[] data=packet.getData();
          String receiveData=new String(data,0,data.length);
          System.out.println(receiveData.trim());
          if(receiveData.trim().equals("再见")){
              break;
          }
      }
      socket.close();
    }
}

URL:统一资源定位符

URL常用方法:

public class URLDemo {
    public static void main(String[] args) throws MalformedURLException {
        URL url=new URL("https://mp.csdn.net/mp_blog/creation/editor/126768748");
        System.out.println(url.getProtocol()); //得到协议名
        System.out.println(url.getHost());   //得到主机名
        System.out.println(url.getPort());   //端口
        System.out.println(url.getPath());  //文件地址
        System.out.println(url.getFile());  //得到文件
        System.out.println(url.getQuery()); //url查询的名字
    }
}

URL下载资源:

public class URLDemo {
    public static void main(String[] args) throws IOException {
       //1.下载地址
        URL url=new URL("https://mp.csdn.net/mp_blog/creation/editor/126768748");
       //2.连接到这个资源
       HttpURLConnection urlConnectio =(HttpURLConnection) url.openConnection();
        InputStream inputStream= urlConnectio.getInputStream();
        FileOutputStream fos=new FileOutputStream("test.text");
        byte[] buffer=new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        urlConnectio.disconnect();//断开连接
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前段被迫创业

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值