Java网络编程

一、什么是计算机网络

打电话--连接--接了--通话    TCP

发信息--发送就完事了--接收  UDP(可能会掉包)

javaweb:网页编程   B/S架构(浏览器)

网络编程:TCP/IP     C/S架构(客户端)

二、网络通信的两个要素

1.如何实现网络通信?

1.通信双方地址:ip   端口号

2.网络通信的协议:Java网络编程_第1张图片

三、IP地址

ip地址:InetAddress

唯一定位一台网络上计算机

127.0.0.1:自己的电脑 localhost

ip地址的分类:

1.ipv4/ipv6:ipv4  127.0.0.1,4个字节组成(每个字节长度0-255,十进制点隔开)

                    ipv6   2409:8a20:2c19:7b60:e1be:5973:c280:e399(十六进制)    128位(2的128次方个字节)   8个无符号整数

2.公网(互联网)-私网(局域网)

ABCD类地址

192.168.xx.xx 局域网 专门给组织内部使用

域名:记忆ip问题   IP:www.vip.com

package WangLuoBianCheng;

import java.net.InetAddress;
import java.net.UnknownHostException;

// 测试IP
public class TestInetAddress {
     public static void main(String[] args) {
         try {//查询本机地址
             InetAddress inetAddress3= InetAddress.getByName("localhost");
             System.out.println(inetAddress3);
             InetAddress inetAddress4= InetAddress.getLocalHost();
             System.out.println(inetAddress4);
             InetAddress inetAddress1= InetAddress.getByName("127.0.0.1");
             System.out.println(inetAddress1);
                     //查询网络ip地址
             InetAddress inetAddress2= InetAddress.getByName("www.baidu.com");
             System.out.println(inetAddress2);
         } catch (UnknownHostException e) {
             throw new RuntimeException(e);
         }
     }
}

四、端口Port

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

不同的进程有不同的端口号!用来区分软件!

被规定为0-65535

包含有有TCP,UDP:总共65535*2        TCP为80,UDP也可以是80,但在单个协议下,端口号不能冲突

端口分类:

1.公有端口 0-1023(尽量不要占用) 例:HTTP:80    HTTPS:443    FTP(文件传输):21

Telent(远程控制):23

2.程序注册端口:1024-49151,分配用户或者程序

Tomcat:8080    MySQL:3306    Oracle:1521

3.动态、私有(也不要放在这里面):49152-65535

五、通信协议

网络通信协议:1.速率2.传输码率3.代码结构4.传输控制...

TCP/IP协议簇(实际上是一组协议)   重要的有:TCP:用户传输协议   UDP:用户数据报协议

出名的协议:TCP:用户传输协议    IP:网络互连协议

TCP UDP对比

TCP:打电话

连接,稳定

三次握手,四次挥手:至少需要三次交流才能进行连接,a你在吗b我在a我也在。    至少需要四次交流才能断开连接:a我要走了  b我也要走了  b你走了嘛   a我走了

客户端,服务端

传输完成,释放连接,效率低

UDP:发短信

不连接,不稳定

没有明确客户、服务端的界限

不管有没有准备好,都可以发给你

六、TCP实现聊天

客户端

1.连接服务器Socket

2.发送消息

package WangLuoBianCheng.lesson02;

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

//客户端
public class TcpClientDemo01 {
    public static void main(String[] args) {
        //IP地址不用提高定义域
        Socket socket=null;
        OutputStream os=null;
        //1.要知道服务器的地址
        try {
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            //2.端口号
            int port=9999;
            //3.创建一个socket连接
            socket = new Socket(serverIP,port);
            //4.发送消息 IO流
             os = socket.getOutputStream();
            os.write("你好".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
         if (os!=null){
             try {
                 os.close();
             } catch (IOException e) {
                 throw new RuntimeException(e);
             }
         }
         if (socket!=null){
             try {
                 socket.close();
             } catch (IOException e) {
                 throw new RuntimeException(e);
             }
         }
        }
    }
}

服务端

1.建立服务的端口ServerSocket

2.等待用户的链接accept

3.接受用户的信息

package WangLuoBianCheng.lesson02;

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 {
                //1.我得先有一个地址
                 serverSocket = new ServerSocket(9999);//serversocket服务端套接字
               //while (true)    循环接受
                //2.等待客户端连接过来
                socket = serverSocket.accept();//此时socket与客户端建立联系
                //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) {
                        throw new RuntimeException(e);
                    }
                }
                if (is!=null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (socket!=null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (serverSocket!=null){
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

            }
        }
    }
}

七、文件上传

客户端

package WangLuoBianCheng.lesson01;

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


public class TcpClientDemo02 {
    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("1.jfif"));
        //4.写出文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len=fis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }
        //通知服务器,我已经传输完了
        socket.shutdownOutput();

        //确定服务器接受完毕,才能够断开连接
        InputStream inputStream = socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer2 = new byte[1024];
        int len2;
        while ((len2=inputStream.read(buffer2))!=-1){
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());
        //5.关闭资源


        fis.close();
        os.close();
        socket.close();


    }
}

服务端

package WangLuoBianCheng.lesson01;

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("receive.jfif"));
        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());


        //关闭资源
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

八、UDP消息发送

发短息:不用连接,需要知道对方的地址

发送端

package WangLuoBianCheng.lesson03;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

//不需要连接服务器
public class UdpClientDemo01 {
    public static void main(String[] args) throws IOException {
        //1.建立一个Socket
        DatagramSocket socket = new DatagramSocket(0);
        //2.建个包
        String msg="你好啊,服务器!";
        //发送给谁
        InetAddress localhost = InetAddress.getByName("localhost");
        int port=9090;
        //数据,数据的长度,要发送给谁
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);

        //3.发送包
        socket.send(packet);

        //4.关闭流
        socket.close();
    }
}

接收端

package WangLuoBianCheng.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//还要等待客户端的链接
public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
   //开放端口
        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聊天实现

循环发送消息

package WangLuoBianCheng.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UdpSenderDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
        //准备数据:控制台读取System.in
        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("bye")){
               break;
           }
       }

    }
}

循环接收消息

package WangLuoBianCheng.chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpReceiveDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);

        while (true) {
            //准备接收包裹
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            socket.receive(packet);//阻塞式接收包裹

            //断开连接  说bye   自己输入bye来结束
            byte[] data = packet.getData();
            String receiveData = new String(data,0, packet.getLength());
            System.out.println(receiveData);
            if (receiveData.equals("bye")){
                break;
            }

        }
    }
}

十、URL

统一资源定位符,定义互联网上的某一个资源

DNS域名解析(讲域名变成IP)   www.baidu.com(域名)   xxx.xxx..xx(IP) 域名的本质还是IP,域名更好记

https://www.baidu.com/

协议://ip地址:端口号

package WangLuoBianCheng.lesson04;

import Base.HelloWorld;

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

public class UrlDown {
    public static void main(String[] args) throws Exception{
        //1.下载地址
        URL url = new URL("https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%9B%BE%E7%89%87&hs=0&pn=0&spn=0&di=7117150749552803841&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&ie=utf-8&oe=utf-8&cl=2&lm=-1&cs=2196812579%2C178847292&os=2981951213%2C133282478&simid=3419287875%2C189417273&adpicid=0&lpn=0&ln=30&fr=ala&fm=&sme=&cg=&bdtype=0&oriquery=%E5%9B%BE%E7%89%87&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242332225H9-0-lp.jpg%26refer%3Dhttp%3A%2F%2Fimg.jj20.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1666433043%26t%3D31583ae04a8f6793190cf2b1998c7eb7&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3B33da_z%26e3Bv54AzdH3F9hAzdH3Fu3AzdH3Fnmbnba_z%26e3Bip4s&gsm=100000000000001&islist=&querylist=&dyTabStr=MCwzLDEsNiw0LDUsMiw3LDgsOQ%3D%3D");

        //2.连接到这个资源 HTTP
        HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("555.jfif");

        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接


    }
}

你可能感兴趣的:(网络,服务器,运维)