初识网络编程

网络编程

狂神网络编程

概述

网络编程的目的:数据交换,通信

想要达到的效果:

  1. 定位到网络上的一台主机上的某个应用资源 ip地址:端口

javaweb:网页编程 B/S架构

网络编程:TCP/IP C/S架构

网络通信的要素

IP

IP地址:InetAddress

  • 唯定位一台网络上计算机
  • 127.0.0.1:本机localhost
  • IP地址分类
    • ipv/ipv6
      • 公网(互联网)-私网(局域网)
import java.net.InetAddress;
import java.net.UnknownHostException;
//测试IP
public class TestInetAddress {
    public static void main(String[] args) {
        try {
            //查询本机地址
            InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress);
            InetAddress inetAddress2=InetAddress.getByName("localhost");
            System.out.println(inetAddress2);
            InetAddress inetAddress3=InetAddress.getLocalHost();
            System.out.println(inetAddress3);
            //查询网站ip地址
            InetAddress inetAddress1=InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress1);
            //常用方法
            System.out.println(inetAddress1.getAddress());
            System.out.println(inetAddress1.getCanonicalHostName());//规范的名字
            System.out.println(inetAddress1.getHostAddress());//ip
            System.out.println(inetAddress1.getHostName());//域名或者自己电脑的名字
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

端口

  • 不同的进程有不同的端口号,用来区分软件!

  • 被规定0-65535

  • 分为TCP,UDP,每个协议下都有65535,单一协议下端口号不能冲突

  • 端口分类

    • 共有端口0-1023
      • HTTP:80
      • HTTPS:443
      • FTP:21
      • Telent:23
    • 程序注册端口:2014-49151,分配给用户或程序
      • Tomcat:8080
      • MySQL:3306
      • Oracle:1521
    • 动态、私有:49152-65535

    dos命令

    netstat -ano   查看所有端口
    netstat -ano|findstr "5900" #查看指定端口
    tasklist|findstr "3600" # 查看指定端口的进程
    
    import java.net.InetSocketAddress;
    
    public class TestSocketAddress {
        public static void main(String[] args) {
            InetSocketAddress inetSocketAddress=new InetSocketAddress("localhost",8080);
            System.out.println(inetSocketAddress);
            System.out.println(inetSocketAddress.getAddress());
        }
    }
    

    通信协议

    TCP:用户传输协议

    UDP:用户数据协议

    IP:网络互联协议

    TCP,UDP对比:

    • TCP
      • 需要建立连接,稳定可靠
      • 三次握手,四次挥手
      • 客户端跟服务端
      • 传输完成释放连接,效率低
    • UDP
      • 不连接,不稳定
      • 客户端服务端没有明确界限
      • 不用建立连接就可以进行发送

TCP实现聊天

客户端:

  1. 连接服务器Socket
  2. 发送消息

服务器:

  1. 建立服务的端口ServerSocket
  2. 等待用户的连接accept
  3. 接受用户的消息
//客户端
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpCustomer {
    public static void main(String[] args) {
        Socket socket=null;
        OutputStream outputStream=null;
        try {
            //1.获取服务器地址,端口号
            InetAddress ServerIP = InetAddress.getByName("127.0.0.1");
            int port=9999;
            //2.创建socket连接
            socket = new Socket(ServerIP, port);
            //3.发送消息IO流
            outputStream = socket.getOutputStream();
            outputStream.write("hello,world!".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();
                }
            }
        }
    }
}
//服务器端
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream inputStream=null;
        ByteArrayOutputStream baos=null;
        try {
            //1.创建一个套接字地址
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接
            while (true) {
                socket=serverSocket.accept();
                //3.读取客户端消息
                inputStream=socket.getInputStream();
                //管道流
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                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 (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

TCP传输文件

//客户端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TcpCustomer2 {
    public static void main(String[] args) {
        try {
            //1.创建一个socket连接
            Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9000);
            //2.创建一个输出流
            OutputStream os=socket.getOutputStream();
            FileInputStream fis=new FileInputStream(new File("myjpg.jpg"));
            byte[] buffer=new byte[1024];
            int len;
            while((len=fis.read(buffer))!=-1){
                os.write(buffer,0,len);
            }
            //通知服务器,我已经结束了
            socket.shutdownOutput();
            //确定服务器接受完毕,才能断开连接
            InputStream inputStream=socket.getInputStream();
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            byte[] buffer2 = new byte[2014];
            int len2;
            while((len2=inputStream.read(buffer2))!=-1){
                baos.write(buffer2,0,len2);
            }
            System.out.println(baos.toString());
            baos.close();
            inputStream.close();
            fis.close();
            os.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//服务器端
import com.sun.xml.internal.bind.v2.util.ByteArrayOutputStreamEx;

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

public class TcpServer2 {
    public static void main(String[] args) {

        try {
            //1.建立套接字
            ServerSocket serverSocket = new ServerSocket(9000);
            //2. 等待连接
            Socket socket=serverSocket.accept();
            //3.获取输入流
            InputStream is = socket.getInputStream();
            //4.文件输出
            FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
            byte[] buffer=new byte[1024];
            int len;
            while((len= is.read(buffer))!=-1){
                fos.write(buffer,0,len);
            }
            //通知客户端接受完毕可以断开连接
            OutputStream os=socket.getOutputStream();
            os.write("接受完毕,可以断开".getBytes());
            //关闭资源
            os.close();
            fos.close();
            is.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Tomcat

服务端

  • 自定义S
  • Tomcat服务器S

客户端

  • 自定义C
  • 浏览器B

UDP消息方法

不用建立链接,只需知道对方地址

import java.net.DatagramPacket;
import java.net.DatagramSocket;
//需要客户端连接
public class UDPServer {
    public static void main(String[] args) throws Exception{
        //开放端口
        DatagramSocket datagramSocket = new DatagramSocket(9000);
        //接受数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        datagramSocket.receive(packet);//阻塞接受
        System.out.println(new String(packet.getData(),0, packet.getLength()));
        //关闭连接
        datagramSocket.close();
    }
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
//不需要连接服务器
public class UDPDemo {
    public static void main(String[] args) throws Exception  {
        //1.建立一个Socket
        DatagramSocket datagramSocket = new DatagramSocket();
        //2.建个包
        String message="hello world!";
        InetAddress localhost=InetAddress.getByName("localhost");
        int port=9000;
        DatagramPacket packet = new DatagramPacket(message.getBytes(), 0, message.getBytes().length, localhost, port);
        //3.发送包
        datagramSocket.send(packet);
        //4.关闭流
        datagramSocket.close();
    }
}

UDP聊天实现

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

public class UDPReceiver {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);
        while(true){
            //准备接受包裹
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
            socket.receive(packet);
            //断开连接
            byte[] data=packet.getData();
            String receiveData= new String(data,0, data.length);
            System.out.println(receiveData);
            if (receiveData.equals("bye")) {
                break;
            }
        }
        socket.close();
    }
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

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

多线程

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//接受线程
public class ReceiveThread implements Runnable {
    int fromPort;
    DatagramSocket socket=null;

    public ReceiveThread(int fromPort) throws Exception{
        this.fromPort = fromPort;
        socket=new DatagramSocket(fromPort);
    }

    @Override
    public void run() {
        while(true){
            try {
            //准备接受包裹
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
                socket.receive(packet);
                //断开连接
                byte[] data=packet.getData();
                String receiveData= new String(data,0, data.length);
                System.out.println(Thread.currentThread().getName()+":"+receiveData);
                if (receiveData.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
//发送线程
public class SendThread implements Runnable{
    DatagramSocket socket=null;
    BufferedReader reader=null;
    private int fromPort;
    private String toIP;
    private int toPort;

    public SendThread(int fromPort, String toIP, int toPort) throws Exception {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        this.socket = new DatagramSocket(fromPort);
        this.reader = new BufferedReader(new InputStreamReader(System.in));
    }

    @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();
    }
}
//学生端
public class TalkStudent {
    public static void main(String[] args) throws Exception{
        new Thread(new SendThread(6666,"localhost",8888)).start();
        new Thread(new ReceiveThread(5555),"老师").start();
    }
}
//教师端
public class TalkTeacher {
    public static void main(String[] args) throws Exception{
        new Thread(new SendThread(3333,"localhost",5555)).start();
        new Thread(new ReceiveThread(8888),"学生").start();
    }
}

URL

统一资源定位符:定位资源

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

//URL方法
import java.net.MalformedURLException;
import java.net.URL;

public class URLDemo {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/hellowprld/index.jsp?username=kuangshen&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());//参数

    }
}

//抓取资源
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 {
        //1.下载地址
        URL url = new URL("http://localhost:8080/pro/test.txt");
        //2.连接到这个资源HTTP
        HttpURLConnection connection =(HttpURLConnection) url.openConnection();
        InputStream inputStream = connection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream("Security.txt");
        byte[] buffer=new byte[1024];
        int len;
        while ((len=inputStream.read(buffer,0, buffer.length))!=-1){
            fileOutputStream.write(buffer,0,len);//写出数据
        }
        fileOutputStream.close();
        inputStream.close();
        connection.disconnect();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值