网络编程-狂神

IP

IP地址:

  • 在计算机网络中,唯一确定一台计算机

  • 127.0.0.1:本机回环地址

  • ip地址的分类(IPV4)

    • 分为A类、B类、C类地址,其区别在于A、B、C类子网的个数和所包含的地址个数不同。
    • 局域网网段10.0.0.0~10.255.255.255、172.16.0.0~172.31.255.255、192.168.0.0~192.168.255.255不会在公网中出现
    • 以及一些预留地址
    • 在对应子网中,第一个ip地址表示整个子网的地址,最后一个ip是这个子网的广播地址
//测试
public class Test1  {
    public static void main(String[] args) throws UnknownHostException {
        //使用ip
        InetAddress inetAddress1=InetAddress.getByName("127.0.0.1");
        System.out.println(inetAddress1);
        //使用域名
        InetAddress inetAddress2=InetAddress.getByName("www.csdn.net");
        System.out.println(inetAddress2);
        //LocalHost获取本机回环ip(127.0.0.1)
        InetAddress inetAddress3=InetAddress.getLocalHost();
        System.out.println(inetAddress3);

        //System.out.println(inetAddress2.getAddress());
        //System.out.println(inetAddress2.getCanonicalHostName());
        System.out.println(inetAddress2.getHostAddress());//ip
        System.out.println(inetAddress2.getHostName());//域名
    }
}

端口

  • 不同进程监听不同的端口
  • UDP和TCP协议端口号独立,可以同时有UDP和TCP的80端口
  • 端口号0~65535
  • 其中1023以内端口为约定端口 比如80端口为http服务
  • 1024~49151,分配用户或者应用程序
  • 剩下是动态、私有端口
netstat -ano #查看所有端口
netstat -ano|findstr "XXXXX" #查看指定的端口
tasklist|findstr "XXXX" #查看指定端口发进程

网络通信协议

  • 各个端间通信的标准,使得接收方和发送方对数据没有歧义,同时规定端间数据传输的速率、包/帧结构、实现传输控制等。

  • 主要:TCP/IP协议簇

  • TCP

  • 三次握手 四次挥手,面向连接相对稳定,

  • 客服端

    • 连接服务器Socket
    • 发送消息
      -服务器
    • 建立服务端口ServerSocket
    • 等待用户的连接accept
    • 接受用户的消息
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

//客户
public class Test3 {
   public static void main(String[] args) {
        OutputStream outputStream=null;
        Socket socket=null;
        try {
            //1.获得服务器地址
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port=999;
            //2.创建socket连接
            socket = new Socket(serverIP, port);
            //3.发送消息 IO流
            outputStream = socket.getOutputStream();
            outputStream.write("张书行".getBytes());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket acceptSocket=null;
        InputStream inputStream=null;
        ByteArrayOutputStream byteArrayOutputStream=null;

        while (true){
            try {
                //1.我得有一个地址
                serverSocket = new ServerSocket(999);
                //2.等待客户端连接过来
                acceptSocket = serverSocket.accept();
                //3.读取用户的消息
                inputStream = acceptSocket.getInputStream();

                /*
                //该方法如果读取数据大于1024字节,会造成乱码情形
                byte[] bytes = new byte[1024];
                int len=0;
                while ((len=inputStream.read(bytes))!=-1){
                    String msg = new String(bytes, 0, len);
                    System.out.println(msg);
                }*/

                //管道流
                byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len=0;
                while ((len=inputStream.read(bytes))!=-1){
                    byteArrayOutputStream.write(bytes,0,len);
                }

                System.out.println(byteArrayOutputStream.toString());

            } catch (IOException  e) {
                e.printStackTrace();
            } finally {
                if (byteArrayOutputStream!=null){
                    try {
                        byteArrayOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (acceptSocket!=null){
                    try {
                        acceptSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (serverSocket!=null){
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

文件上传和 下载

客服端:

public class textUpload {
    public static void main(String[] args) throws Exception {
        //1.创建一个Socket连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
        //2.创建一个输出流
        OutputStream outputStream = socket.getOutputStream();
        //3.读取文件
        FileInputStream fileInputStream = new FileInputStream("D://张书行_自我批评.docx");

        //4.写出文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        //通知服务器,我已经结束了
        socket.shutdownOutput();
        //确定服务器接收完毕,才能断开连接
        InputStream inputStream = socket.getInputStream();
        byte[] buffer2 = new byte[1024];
        int len2;
        // 接收字符串使用字符串的管道流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        while ((len2=inputStream.read(buffer2))!=-1){
            byteArrayOutputStream.write(buffer2,0,len2);
        }
        System.out.println(byteArrayOutputStream.toString());
        //5.关闭资源
        byteArrayOutputStream.close();
        inputStream.close();
        outputStream.close();
        fileInputStream.close();
        socket.close();
    }

}

服务器:

public class text_download {
    public static void main(String[] args) throws Exception {
        //1、创建服务
        ServerSocket serverSocket = new ServerSocket(9999);

        //2、监听客户端的链接
        Socket socket = serverSocket.accept();

        //3、获取输入流
        InputStream inputStream = socket.getInputStream();

        //4、文件输出(文件管道流)
        FileOutputStream fileOutputStream = new FileOutputStream(new File("E://张书行_自我批评.docx"));
        byte[] buffer = new byte[1024];
        int len;

        while ((len = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
        }

        //通知客户端我接收完毕了
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("接收成功".getBytes());
        //关闭资源
        outputStream.close();
        fileOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }

}

udp

客户端

public static void main(String[] args) throws Exception {
        //1、建立一个Socket(udp)
        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 static void main(String[] args) throws Exception {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);

        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length);
        // 阻塞接收
        socket.receive(datagramPacket);

        System.out.println(datagramPacket.getAddress().getHostAddress());
        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));

    }

udp咨询(半双工)

send:

public class send {
    public static void main(String[] args) throws IOException, UnknownHostException, UnknownHostException {
       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("bye".equals(data)){
                break;
            }
        }
        socket.close();
    }
}

receiver:

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);
            //断开连接 bye
            if("bye".equals(receiveData)){
                break;
            }
        }
        socket.close();

    }

UDP聊天(半双工)

TalkSend

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
//发送端
public class TalkSend implements Runnable{
    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String hostname;
    private int toPort;
    //数据初始化
    public TalkSend(int fromPort, String hostname, int toPort) {
        this.fromPort = fromPort;
        this.hostname = hostname;
        this.toPort = toPort;
        try{
            socket= new DatagramSocket(fromPort);
            reader= new BufferedReader(new InputStreamReader(System.in));
        }catch (SocketException e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try{
                String s = reader.readLine();
                byte[] buffer= s.getBytes();
               DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length,new InetSocketAddress(hostname,toPort));

               //发送包
                socket.send(packet);
                if (s.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

TalkReceive

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

//接收端
public class TalkReceive implements Runnable {
    DatagramSocket socket = null;
    private int port;

    public TalkReceive(int port) {
        this.port = port;
        try{
            socket = new DatagramSocket(port);

        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //开放端口


        //接受包
        while (true){
            try{
                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);
                System.out.println(Thread.currentThread().getName()+":"+receiveData);

                if (receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

StudentClient:

public class StudentClient {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555,"localhost",9999)).start();
        new Thread(new TalkReceive(8900),"学生").start();

    }

}

TeacherClient:

public class TeacherClient {
    public static void main(String[] args) {
        new Thread(new TalkSend(7777,"localhost",8900)).start();
        new Thread(new TalkReceive(9999),"老师").start();
    }
}

URL

  • https://www.baidu.com

  • 统一资源定位符:定位互联网上的某一个资源

  • DNS域名解析 www.baidu.com —> xxx.xxxx.xxxx.xxxx

    协议:// ip地址:端口号/项目名/资源

url解析:

public class demo {
    public static void main(String[] args) throws  MalformedURLException {

        URL url = new URL("http://localhost:8080/helloworld/insex" +
                ".jsp?username=subeily&password=123");

        System.out.println(url.getProtocol());  // 协议
        System.out.println(url.getHost());  // 主机IP
        System.out.println(url.getPort());  // 端口
        System.out.println(url.getPath());  // 路径
        System.out.println(url.getFile());  // 文件名
        System.out.println(url.getQuery()); // 参数

    }

}

从互联网上下载内容:

public class internetDownload {
    public static void main(String[] args) throws Exception{

        // 1.下载地址
        URL url = new URL("https://api.bilibili.com/x/player/online/total?cid=132936380&bvid=BV1LJ411z7vY&ts=54179445");
        // 2.连接到这个资源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream is = urlConnection.getInputStream();

        FileOutputStream stream = new FileOutputStream(new File("same.txt"));
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) != -1){
            stream.write(bytes,0,len);
        }

        stream.close();
        is.close();
        urlConnection.disconnect();

    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值