网络编程

网络编程

  

 

 计算机网络:

1--计算机网络是指地理位置不同的具有独立功能的多台计算机及其外部设备,通过通信线路连接起来,
在网络操作系统,网络管理软件及网络通信协议的管理和协调下,实现资源共享和信息传递的计算机系统。
2--网络编程的目的:无线电台.... 传播交流信息,数据交换。通信 3--想要达到这个效果需要什么: 1.如何准确的定位网络上的一台主机 192.168.16.124:端口,定位到这个计算机上的某个资源 2.找到了这个主机,如何传输数据呢?

网络通信的要素

1---如何实现网络的通信?
    通信双方地址:1.ip   2.端口号

2--规则:网络通信的协议 TCP/IP参考模型
    1.应用层  2.传输层 3.网络层 4.数据链路层

IP

ip地址:InetAddress
 1--唯一定位一台网络上计算机
 2--127.0.0.1  本机localhost
 3--ip地址的分类
          1--ipv4/ipv6
              *IPV4 127.0.0.1 ,4个字节组成。
              *Ipv6 128位,8个无符号整数!
          2--公网(互联网)-私网(局域网)
                192.168.xx.xx 专门给组织内部使用的
          3--记忆IP问题!
                IP:www.vip.com
import java.net.InetAddress;
import java.net.UnknownHostException;

//测试ip地址
public class TestInetAddress {

    public static void main(String[] args) {

        //查询本机地址
        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress);
            InetAddress inetAddress3 = InetAddress.getByName("localhost");
            System.out.println(inetAddress3);
            InetAddress inetAddress4 = InetAddress.getLocalHost();
            System.out.println(inetAddress4);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //查询网站ip地址
        InetAddress inetAddress2= null;
        try {
            inetAddress2 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress2);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }


    }
}

端口

import java.net.InetSocketAddress;

public class TestSocketAddress {

    public static void main(String[] args) {

        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
        System.out.println(inetSocketAddress);

        System.out.println(inetSocketAddress.getAddress());
        System.out.println(inetSocketAddress.getHostName());  //地址
        System.out.println(inetSocketAddress.getPort());     //端口
    }
}

 通信协议

 

 

 

 

 TCP实现聊天

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

//客户端
public class TcpClientDemo01 {

    public static void main(String[] args) {

        InetAddress serverIp=null;
        Socket socket=null;
        OutputStream os=null;
        //1.要知道服务器的地址,端口号
        try {
            serverIp=InetAddress.getByName("127.0.0.1");
            int port=9999;
            //创建一个Socket连接
            socket=new Socket(serverIp,port);
            //发送消息IO流
            os=socket.getOutputStream();
            os.write("你好,欢迎来到Java的世界".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();
                }
            }
        }
    }
}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端  先开启服务器端
public class TcpServerDemo01 {

    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;
        //我得有一个地址
        try {
             serverSocket = new ServerSocket(9999);

             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();
                }
            }
            try {
                is.close();
                socket.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
客户端:1--连接服务器Socket
            2--发送消息
服务器:1--建立服务的端口ServerSocket
            2--等待用户的连接 accep
            3.接收用户的消息

 TCP实现文件上传

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

//客户端
public class TcpClientDemo02 { public static void main(String[] args) throws IOException { //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("1.jpg")); //4.写出文件 byte[] buffer = new byte[1024]; int len; while ((len=fis.read(buffer))!=-1){ os.write(buffer,0,len); } socket.shutdownOutput(); //我已经传输完了 //确定服务器接受完毕,才能够断开 InputStream is = socket.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer2 = new byte[1024]; int len2; while ((len2=is.read())!=-1){ baos.write(buffer2,0,len2); } //5.关闭资源 fis.close(); os.close(); socket.close(); } }
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerDemo02 {

    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("service.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }

        //通知客户端我接受完毕了
        OutputStream os = socket.getOutputStream();
        os.write("我接受完毕了,你可以断开了".getBytes());

        os.close();
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

UDP发送消息

import java.io.IOException;
import java.net.*;

//不需要连接服务器  客户端
public class UdpClientDemo01 {

    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 datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
       //3.发送
        socket.send(datagramPacket);
        //4.关闭
        socket.close();

    }
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

//还是要等待客户端的连接
public class UdpServiceDemo01 {

    public static void main(String[] args) throws IOException {

        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(datagramPacket);
        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));

        //关闭连接
        socket.close();
    }
}

UDP实现聊天

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UdpSenderDemo01 {

    public static void main(String[] args) throws IOException {

        //建立socket
        DatagramSocket socket = new DatagramSocket(8888);

        BufferedReader reader=null;
        //准备数据:控制台读取System.in
        reader = new BufferedReader(new InputStreamReader(System.in));

        while (true){
            String data=reader.readLine();
            byte[] datas=data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas, 0, data.length(), new InetSocketAddress("localhost", 6666));

            socket.send(packet);
            if(data.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpReceiveDemo01 {

    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);      //阻塞式接收包裹

            //断开连接 bye
            byte[] data = packet.getData();
            String recevieDatas=new String(data,0,packet.getLength()).trim();

            System.out.println(recevieDatas);

            if(recevieDatas.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

URL

 

 

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import java.net.URL;

public class UrlDown {

    public static void main(String[] args) throws IOException {
        //1.下载地址
        URL url=new URL("https://m701.music.126.net/20220220214522/e7e463d84bf77af7a6ac38c9a29713ad/jdyyaac/565b/010f/530f/a16a59d48d6e2e8b2077deaca4284ca9.m4a");

        //2.连接到这个资源 HTTP
        HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();

        InputStream inputStream=urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("9.m4a");

        byte[] bytes=new byte[1024];
        int len;
        while ((len=inputStream.read())!=-1){
            fos.write(bytes,0,len);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();

    }
}

 

 

posted @ 2022-02-19 22:39  十三加油哦  阅读(66)  评论(0)    收藏  举报