【TCP/IP】简单几行Java代码实现迅雷功能,下载图片、音乐、视频、电影

时光怂恿深爱的人放手 提交于 2020-10-01 13:24:49

一、TCP与UDP

TCP(Transmission Control Protocol,传输控制协议)协议:负责将要传输的文件分段 进行传输,一般用于建立会话 ,其基本特性是可靠传输 、流量控制,所谓三握手、四挥手也是基于TCP协议的

UDP(User Data Protocol,用户数据报协议)协议:一个数据包就能够完成数据通信 ,数据包不分段 ,不需要建立会话 ,不需要流量控制 ,属于不可靠传输 , 屏幕广播 、多播 、广播都是基于UDP协议

二、TCP实现数据上传

1、TCP服务端

package com.tcpip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerTest {
    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(new File("copy.png"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        //5、关闭资源
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

2、TCP客户端

package com.tcpip;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientTest {
    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("01.png"));
        //4、写入文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len=fis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }
        //5.关闭资源
        fis.close();
        os.close();
        socket.close();
    }
}

3、测试

三、UDP实现数据上传

1、UDP接收端

package com.tcpip;

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

public class UdpServerTest {
    public static void main(String[] args) throws Exception {
        //1、开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //2、接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(),0,packet.getData().length));
        //3、关闭连接
        socket.close();
    }
}

2、UDP发送端

package com.tcpip;

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

public class UdpClientTest {
    public static void main(String[] args) throws Exception {
        //1、建立一个socket
        DatagramSocket socket = new DatagramSocket();
        //2、建个包
        String msg = "UDP 测试";
        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();
    }
}

3、测试

四、UDP实现多线程在线咨询

1、发送端

package com.tcpip;

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

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

2、接收端

package com.tcpip;

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);
               //断开连接bye
               byte[] data = packet.getData();
               String receiveData = new String(data,0,data.length);
               System.out.println(msgFrom + ":" + receiveData);
               if(receiveData.equals("bye")){
                   break;
               }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

3、学生

package com.tcpip;

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

4、老师

package com.tcpip;

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

5、开始聊天啦,模拟请假

五、Java下载URL网络资源(图片、音乐、视频、电影)

一、前言

今天学习了一下FTP/IP的相关知识,发现一个强大的功能,用Java下载URL网络资源,据说收费的也能下! 学编程真好,Java真好。

二、代码实例

package com.tcpip;

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 {
        URL url = new URL("https://vodkgeyttp8.vod.126.net/cloudmusic/776e/core/e166/8847b8c0360e7e3314cf773848e943cd.mp4?wsSecret=ebc2bc0c17347de34a5b1246c3be0b34&wsTime=1598776625");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream is = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("FOR LOVE.mp4");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
             fos.write(buffer,0,len);
        }
        fos.close();
        is.close();
        urlConnection.disconnect();
    }
}

三、执行效果

1、搜索网络资源URL

2、代码下载效果

3、视频播放 

 

上一篇:TCP/IP 基础知识总结(绝对经典)

下一篇:【TCP/IP】使用C#实现websocket服务端与客户端通信

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!