网络编程

2021/4/19 20:28:44

本文主要是介绍网络编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. 基础概念

计算机网络,网络通信的两个要素,IP地址(主机),端口Port(软件),通信协议(TCP/IP,三次握手四次挥手)

2. TCP实现聊天

客户端:

  • 连接服务器Socket
  • 发送消息

服务器:

  • 建立服务的端口ServerSocket
  • 等待用户的链接accept
  • 接收用户的消息

示例:

创建Client类:

package com.netprogram;

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) throws IOException {

        Socket socket = null;
        OutputStream os = null;

        try {
            //1. 要知道服务器的地址
            InetAddress serverIp = InetAddress.getByName("127.0.0.1");
            //2. 需要端口号
            int port = 9999;
            //3. 创建一个socket连接
            socket = new Socket(serverIp,port);
            //4. 发送消息
            os = socket.getOutputStream();
            os.write("欢迎连接".getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //关闭资源,用try{}catch{}按顺序关,JDK1.7之后有了try-with-resource处理机制简化代码
            if (os != null){
                os.close();
            }
            if (socket != null){
                socket.close();
            }

        }


    }
}

创建Server类:

package com.netprogram;

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) throws IOException {

        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;

        try {
            //1. 需要有一个地址
            serverSocket = new ServerSocket(9999);
            /*
            //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());
            */

            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){
                baos.close();
            }
            if (is != null){
                is.close();
            }
            if (socket != null){
                socket.close();
            }
            if (serverSocket != null){
                serverSocket.close();
            }

        }

    }

}

结果:

e96a88b69b1ffa3150a9c2b9754f101.png

关闭连接简化机制:

try-with-resourse

3. TCP文件上传实现

客户端:

package com.netprogram.demo02;

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

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

        //5. 通知服务器已经发送
        socket.shutdownOutput();

        //6.确定服务器接收完毕,才能够断开连接
        InputStream ips = socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer1 = new byte[2048];
        int len1;
        while ((len1 = ips.read(buffer1))!=-1){
            baos.write(buffer1,0,len1);
        }

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

        //7.关闭资源
        baos.close();
        ips.close();
        fis.close();
        os.close();
        socket.close();

    }
}

服务端:

package com.netprogram.demo02;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerDemo02 {
    public static void main(String[] args) throws Exception {
        //1. 创建服务
        ServerSocket serverSocket = new ServerSocket(9000);
        //2.监听客户端的连接
        Socket socket = serverSocket.accept(); //阻塞式监听
        //3. 获取输入流
        InputStream is = socket.getInputStream();
        //4. 文件输出
        FileOutputStream fos = new FileOutputStream("IUCopy.jpg");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        //5. 通知客户端接收完毕
        OutputStream ops = socket.getOutputStream();
        ops.write("接收完毕,允许断开".getBytes());

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

    }
}

4. 初识Tomcat

服务端

  • 自定义 S
  • Tomcat服务器(Java后台开发) S

客户端:

  • 自定义 C
  • 浏览器 B

解压Tomcat包,打开bin目录中的starup.bat,启动完毕,浏览器输入localhost:8080即可进入网站

5. UDP

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

没有真正的客户端、服务端概念

6. UDP消息发送

发送端:

package com.netprogram.demo03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

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

        //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.getBytes().length,localhost,port);

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

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

接收端:

package com.netprogram.demo03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;

//还是需要等待发送端的连接
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()));
        //关闭连接
        socket.close();
    }
}

7. UDP聊天实现

单方发送接收消息

发送消息:

package com.netprogram.demo04;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
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 Exception{

        DatagramSocket socket = new DatagramSocket(8888);

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

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

        socket.send(packet);

        socket.close();
    }
}

接收消息:

package com.netprogram.demo04;

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

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

            byte[] data = packet.getData();
            String data1 = new String(data,0, data.length);

            System.out.println(data1);
            System.out.println(data1.length());

            if (data1.trim().equals("bye")){ //字符数组除了bye还有0值,转换成String都是空格,所以需要trim减掉多余部分
                break; //退出循环,关闭连接
            }
        }

        socket.close();

    }
}

在线咨询

两个人都可以是接收方、发送方

示例:

创建TalkReceive类:

package com.netprogram.demo05;

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;
    private String msgFrom;

    public TalkReceive(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 data1 = new String(data, 0, data.length);

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

                if (data1.trim().equals("bye")) { //字符数组除了bye还有0值,转换成String都是空格,所以需要trim减掉多余部分
                    break; //退出循环,关闭连接
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        socket.close();
    }
}

创建TalkSend类:

package com.netprogram.demo05;

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);
        } catch (SocketException e) {
            e.printStackTrace();
        }

        reader = new BufferedReader(new InputStreamReader(System.in));

    }

    @Override
    public void run() {

        while (true) {

            try {
                String data = reader.readLine();
                byte[] data1 = data.getBytes();
                DatagramPacket packet = new DatagramPacket(data1,0, data1.length,new InetSocketAddress(this.toIp,this.toPort));

                socket.send(packet);

                if (data.equals("bye")){
                    break;
                }

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

        }

        socket.close();
    }
}

创建TalkStudent类:

package com.netprogram.demo05;

public class TalkStudent {
    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend(6666,"Localhost",8888)).start();
        new Thread(new TalkReceive(9999,"Teacher")).start();

    }
}

创建TalkTeacher类:

package com.netprogram.demo05;

public class TalkTeacher {

    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend(7777,"Localhost",9999)).start();
        new Thread(new TalkReceive(8888,"Student")).start();
    }
}

学生端结果:

2cad6341e47618e6ed3498089d841de.png

教师端结果:

22a37b71375071b60e9945976d5f569.png

(两边都输入bye可以结束程序)

8. URL下载网络资源

URL(uniform resourse locator):统一资源定位符,定位互联网上的某一个资源

DNS域名解析:将形如www.baidu.com的域名解析成IP地址

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

示例:

package com.netprogram.demo06;

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

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

        //1. 下载地址
        URL url = new URL("http://localhost:8080/yue/important.txt");
        //2. 连接到这个资源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

        //3. 写文件
        InputStream is = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("f:\\example.txt");

        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len); //写数据
        }

        //4. 关资源,断连接
        fos.close();
        is.close();
        urlConnection.disconnect();

    }

}


这篇关于网络编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程