网络编程详解

一、Ip地址

1.使用方法

目的:获得本地ip,以及常用方法的使用
package com.Tang.net;

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

public class InetAddressTest {
    public static void main(String[] args) {
        try {
            //查询本机地址
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress);

            InetAddress inetAddress1 = InetAddress.getByName("localhost");
            System.out.println(inetAddress1);

            InetAddress inetAddress2 = InetAddress.getLocalHost();
            System.out.println(inetAddress2);
            System.out.println("==================");
            //常用方法
            System.out.println(inetAddress1.getHostName());//域名或者自己电脑的名字
            System.out.println(inetAddress1.getHostAddress());//ip
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

运行结果图

二、端口

1.作用

   端口号表示计算机上的一个程序的进程:       不同的进程有不同的端口号!用来区分软件!       被规定为0-65535

2.端口分类

   共有端口0 - 1023       Http : 80       Https: 443       Ftp : 21       Telent : 23    程序注册端口:2014-29151       Tomcat : 8080       MySQL :3306       Oracle :1521    动态、私有:49152-65535
package com.Tang.net;

import java.net.InetSocketAddress;

public class InetSocketAddressTest {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8080);
        InetSocketAddress inetSocketAddress1 = new InetSocketAddress("localhost",8080);
        System.out.println(inetSocketAddress);
        System.out.println(inetSocketAddress1);
        System.out.println("===============");
        //常用方法
        System.out.println(inetSocketAddress.getAddress());
        System.out.println(inetSocketAddress.getHostName());
        System.out.println(inetSocketAddress.getPort());

    }
}

运行结果图

三、Tcp

需要建立连接:也就是客户端必须与服务器端建立连接,在没有服务器端的情况下,运行客户端的代码就会报ConnectException

1.实现消息发送

客户端代码
package com.Tang.net.tcp;

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

public class TcpClintTest {
    public static void main(String[] args){
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.要知道服务器端的地址和端口号
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            int port = 999;
            //2.创建一个socket连接
            socket = new Socket(inetAddress, port);
            //3.创建一个输出流
            os = socket.getOutputStream();
            os.write("欢迎进入Twq的博客,创作不易,多多点赞收藏".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//流的关闭
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

服务器端代码

package com.Tang.net.tcp;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;

public class TcpServerTest {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        try {
            //1.提供服务器端的端口号
            serverSocket = new ServerSocket(999);
            while(true){
                //2.等待客户端连接
                accept = serverSocket.accept();
                //3.读取客户端信息
                is = accept.getInputStream();
                //管道流去读取防止出现乱码的情况
                bos = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while((len = is.read(bytes))!= -1){
                    bos.write(bytes,0,len);
                }
                System.out.println(bos.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //流的关闭
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept != null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

运行结果图

2.实现文件发送与接收

服务器端代码
package com.Tang.net.tcp;

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

public class FileTcpServerTest {
    public static void main(String[] args)  {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fos = null;
        OutputStream os = null;
        try {
            //1.提供端口号
            serverSocket = new ServerSocket(9000);
            //监听客户端的连接
            socket = serverSocket.accept();
            //获取客户端的输入流
            is = socket.getInputStream();
            //文件输出
            fos = new FileOutputStream(new File("tx1.jpg"));
            byte[] bytes = new byte[1024];
            int len;
            while((len = is.read(bytes))!= -1){
                fos.write(bytes,0,len);
            }
            //告知客户端,服务器端已接收完毕
            os = socket.getOutputStream();
            os.write("我已接收完毕,你可已断开了".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//关闭流
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is != null){
                try {
                    is.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();
                }
            }
        }
    }
}

客户端代码

package com.Tang.net.tcp;

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

public class FileTcpClintTest {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        FileInputStream fis = null;
        try {
            //1.获取服务器端的地址和端口号
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
            //2.创建输出流
            os = socket.getOutputStream();
            //3.读取图片文件
            fis = new FileInputStream(new File("tx.jpg"));
            //向服务器端写出图片
            byte[] bytes = new byte[1024];
            int len;
            while((len = fis.read(bytes))!= -1){
                os.write(bytes,0,len);
            }
            //通知服务器端,客户端已经发送完毕
            socket.shutdownOutput();

            //客户端接收服务器端发送的已接收完毕的信息
            inputStream = socket.getInputStream();
            //输出的管道流
            baos = new ByteArrayOutputStream();

            byte[] bytes1 = new byte[2014];
            int len1;
            while((len1 = inputStream.read(bytes1))!= -1){
                baos.write(bytes1,0,len1);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//关闭流
            if(baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }    
        
    }
}

运行结果图

四、UDP

不需要建立连接:也就是发送端只需要知道要接收端主机的ip和端口号就可以进行消息的发送,不需要与接收端进行连接

1.实现发送与接收方的单个数据的发送与接收

发送方代码:
package com.Tang.net.udp;

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


//不需要连接服务器
public class UdpClintTest {
    public static void main(String[] args) throws Exception {
        //1.建立一个socket
        DatagramSocket socket = new DatagramSocket();
        //要发送的对象
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        //2.建立一个包
        String msg = "你好服务器";
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);

        //发送包裹
        socket.send(packet);
        socket.close();
    }
}

发送方里DatagramPacket里的参数解释看其源码可知

接收方代码

package com.Tang.net.udp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;


public class UdpReceiveTest {
    public static void main(String[] args) throws Exception {
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //接收数据
        byte[] bytes = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        //关闭流
        socket.close();
    }
}

2.实现发送方与接收方消息的持续发送与接收

发送方代码
package com.Tang.net.udp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UdpSendTest {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
        while(true){
            //准备数据,从控制台输入数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String data = reader.readLine();//读取控制台输入的数据
            DatagramPacket packet = new DatagramPacket(data.getBytes(),0,data.getBytes().length,new InetSocketAddress("localhost",6666));
            socket.send(packet);
            if(data.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

接收方代码

package com.Tang.net.udp;

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

public class UdpReceiveTest01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);
        while(true){
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
            socket.receive(packet);
            String reveiveData = new String(packet.getData(), 0, packet.getLength());
            System.out.println(reveiveData);
            if(reveiveData.equals("bye")){
                break;
            }
        }
       socket.close();
    }
}

运行结果图

3.实现发送方与接收方相互发送与接收消息

老师和学生可能既是发送端又是接收端,实现两者相互聊天 发送消息代码
package com.Tang.net.udp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;

import static java.lang.System.*;

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){
            try {
                String data = reader.readLine();
                byte[] bytes = data.getBytes();//不知道为啥哈,这里不单独写,在聊天的过程中会出现中文乱码
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, new InetSocketAddress(this.toIp, this.toPort));
                socket.send(packet);
                if(data.equals("bye")){
                    break;
                }
            } catch (Exception e) {
            e.printStackTrace();
            }
        }
        socket.close();
    }
}

接收消息

package com.Tang.net.udp;

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 msgName;

    public TalkReceive(int port, String msgName) {
        this.port = port;
        this.msgName = msgName;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (true){
                byte[] bytes = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
                socket.receive(packet);

                String receiveData = new String(packet.getData(), 0, packet.getLength());
                System.out.println(msgName + ":" + receiveData);
                if(receiveData.equals("bye")){
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        socket.close();
    }
}

学生端

package com.Tang.net.udp;

public class TalkStudent {
    public static void main(String[] args) {
        new Thread(new TalkSend(666,"localhost",777)).start();//作为发送端时,接收端的端口号为777,自己发出的消息端口号为666
        new Thread(new TalkReceive(888,"老师")).start();//作为接收端时,接收消息的端口号为888
    }
}

老师端

package com.Tang.net.udp;

public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(999,"localhost",888)).start();//作为发送端时,自己发送消息的接口为999,接收方的端口为888
        new Thread(new TalkReceive(777,"学生")).start();//作为接收端时,接收消息的端口号为777
    }
}

运行结果图

五、URL下载

package com.Tang.net.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;
import java.net.URLConnection;

public class URLtest {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://music.163.com/song/media/outer/url?id=1359331363.mp3");
//        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());//参数

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos= new FileOutputStream("j.mp3");

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

posted @ 2022-07-12 20:01  剑断青丝ii  阅读(516)  评论(0编辑  收藏  举报