JAVA网络编程

一、IP

package com.NetCode;

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

public class TestInetAddress {
    public static void main(String[] args) {
        try {
            //查询本机地址
            InetAddress byName = InetAddress.getByName("127.0.0.1");
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println(localHost);
            System.out.println(byName);
            //查询网址ip地址
            InetAddress byName1 = InetAddress.getByName("www.bilibili.com");
            System.out.println(byName1);
            
            //常用方法
            System.out.println(byName1.getAddress());
            System.out.println(byName1.getCanonicalHostName());
            System.out.println(byName1.getHostName());
            System.out.println(byName1.getHostAddress());


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

image

二、端口

1024~49151

netstat -ano #查看所有端口
netstat -ano|findstr"5900"#查看指定的端口
tasklist|findstr"13152" #查看指定端口的进程
package com.NetCode;

import java.net.InetSocketAddress;

public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8080);
        System.out.println(inetSocketAddress1);

        InetSocketAddress inetSocketAddress2 = new InetSocketAddress("localhost", 8080);
        System.out.println(inetSocketAddress2);

        System.out.println(inetSocketAddress1.getAddress());
        System.out.println(inetSocketAddress1.getHostName());
        System.out.println(inetSocketAddress1.getPort());
    }
}

image

三、通信协议

TCP:

  • 连接,稳定

  • 三次握手,四次挥手

  • 客户端、服务端

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

UDP:

  • 不连接,不稳定

  • 客户端、服务端:没有界限

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

四、TCP

4.1发送消息

客户端

  1. 连接服务器Socket
  2. 发生消息
package com.NetCode.TestTCP;

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

//tcp客户端
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket =null;
        OutputStream outputStream =null;
        try {
            //1.要知道服务器的地址
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            //2.端口号
            int port = 9999;
            //创建一个socket连接
           socket = new Socket(serverIP,port);
            //发生消息IO流
           outputStream = socket.getOutputStream();
            outputStream.write("你好我是客户端".getBytes());

        } catch (Exception 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();
                }
            }
        }
    }
}

服务器

  1. 建立服务的端口ServerSocket
  2. 等待用的的链接accept
  3. 接收用户的消息
package com.NetCode.TestTCP;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//tcp服务端
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        //1.我得有一个地址
        try {
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接过来
            socket = serverSocket.accept();
            //3.读取客户端的消息
            inputStream = socket.getInputStream();

            //管道流
            byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len;
            while ((len=inputStream.read(buffer))!=-1){
                byteArrayOutputStream.write(buffer,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 (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

image

4.2文件上传

客户端:

package com.NetCode.TestFileTCP;

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

public class TcpClient {
    public static void main(String[] args) throws Exception {
        //1创建一个socket链接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        //2.创建一个输出流
        OutputStream outputStream = socket.getOutputStream();
        //3.文件流
        FileInputStream fileInputStream = new FileInputStream(new File("temp.jpg"));
        //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();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer02 = new byte[1024];
        int len2;
        while ((len2=inputStream.read(buffer02))!=-1){
            byteArrayOutputStream.write(buffer02,0,len2);
        }
        System.out.println(byteArrayOutputStream.toString());

        //5.关闭资源
        byteArrayOutputStream.close();
        inputStream.close();
        fileInputStream.close();
        outputStream.close();
        socket.close();
    }
}

服务端

package com.NetCode.TestFileTCP;

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

public class TcpServer {
    public static void main(String[] args) throws IOException {
        //1.创建服务
        ServerSocket serverSocket = new ServerSocket(9000);
        //2.监听客户端
        Socket accept = serverSocket.accept();//阻塞式监听,会一直等待客户端链接
        //3.获取输入流
        InputStream inputStream = accept.getInputStream();
        //4.文件输出
        FileOutputStream receive = new FileOutputStream(new File("receive.jpg"));

        byte[] buffer = new byte[104];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            receive.write(buffer,0,len);
        }

        //通知客户端接收完毕
        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("我接收完毕!你可以端口".getBytes());
        receive.close();
        inputStream.close();
        accept.close();
        serverSocket.close();
    }
}

image

image

服务端

  • 自定义S
  • Tomcat服务器S:java后台开发

客户端

  • 自定义C
  • 浏览器B

五、UDP

5.1 发送消息

package com.NetCode.TestUDP;
import java.io.IOException;
import java.net.*;

public class UdpClient {
    public static void main(String[] args) throws IOException {
        //1.建立一个Socket
        DatagramSocket socket = new DatagramSocket(8080);

        //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();


    }
}

接收消息

package com.NetCode.TestUDP;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
//还是要等待客户端的链接!
public class UdpServer {
    public static void main(String[] args) throws Exception {
        //开放端口

        DatagramSocket socket = new DatagramSocket(9090);
        //接收数据包
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf,0,buf.length);

        //阻塞接收
        socket.receive(packet);

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

        //关闭链接
        socket.close();




    }
}

image

5.2 实现聊天

UDPReceiver

package com.NetCode.TestChatUDP;

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

public class UdpReceiveDemo02 {
    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,new InetSocketAddress("localhost",8988));
            
            //阻塞式接收包裹
            socket.receive(packet);
            //断开链接 bye
            byte[] data = packet.getData();
            String receive = new String(data, 0, packet.getLength());
            System.out.println(receive);
            if (receive.trim().equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

UDPSender

package com.NetCode.TestChatUDP;

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 UdpSenderDemo01 {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8988);

        //准备数据:控制台读取system.in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String data = reader.readLine();
            byte[] buffer = data.getBytes();
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress("localhost", 6666));
            socket.send(packet);
            if (data.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

5.3多线程聊天

多线程发送

package com.NetCode.TestChatUDP;

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 toIP;
    private  int    toport;

    public TalkSend(int fromPort, String toIP, int toport) {
        this. fromPort = fromPort;
        this.toIP = toIP;
        this.toport = toport;

        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public TalkSend() {
    }

    @Override
    public void run() {
        while (true){
            try {
                String data = reader.readLine();
                byte[] buf = data.getBytes();
                DatagramPacket packet = new DatagramPacket(buf,0,buf.length,new InetSocketAddress(this.toIP,this.toport));
                socket.send(packet);
                if(data.equals("bye")){
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

多线程接收

package com.NetCode.TestChatUDP;

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

public class TalkRecive implements Runnable{
    DatagramSocket socket = null;
    private  int port;
    private  String msgFrom;

    public TalkRecive(int port,String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        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 receiveeData = new String(data,0, packet.getLength());

              System.out.println(msgFrom+":"+receiveeData);

              if(receiveeData.trim().equals("bye")) {
                  break;
              }

          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      socket.close();
    }
}

开启

package com.NetCode.TestChatUDP;

public class TaikStudent {
    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkRecive(8888,"老师")).start();

    }
}
package com.NetCode.TestChatUDP;

public class TaikTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkRecive(9999,"学生")).start();
    }
}

image

六 URL

6.1统一资源定位符

package com.NetCode.URL;

import java.net.MalformedURLException;
import java.net.URL;

public class TestURLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url =new URL("https://iphoto.macsc.com:443/icon/icon/256/20210423/116308/4662171.png");
        //协议
        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());
    }
}

image

6.2通过URL下载资源

image

package com.NetCode.URL;

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

public class TestURLDemo02 {
    public static void main(String[] args) throws Exception {
       //1.下载地址
        URL url = new URL("http://127.0.0.1:8080/XIANG/temp.txt");
        //2.连接到这个资源HTTP
        HttpURLConnection urlConnection =(HttpURLConnection)url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream urlText = new FileOutputStream("URLText.txt");

        byte[] buffer = new byte[1024];

        int len;

        while ((len=inputStream.read(buffer))!=-1){
            urlText.write(buffer,0,len);
        }
        urlText.close();
        inputStream.close();
        urlConnection.disconnect();

    }
}

image

posted @   项sir  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
XIANGSIR
点击右上角即可分享
微信分享提示