网络编程tcp/ip

如何定义到网络上的一台或多台主机,可以用ping ip的方式

ping baidu.com

找到主机之后如何通讯

IP和端口号

网络通讯协议 udp,tcp

Java中的IP类

ip地址类:InetAddress

IP是唯一定位一台网络上的计算机

127.0.0.1 本机localhost

IP地址

​ IPV4/IPV6

​ IPV4 127.0.01 四个字节组成 0~255 总共有42亿~

​ ipv6 128位,8个无符号整数,类似于这样子的

aaaa:asds:1232:3434:4544:2222:3333:3333

公网(互联网),局域网

192.168.xx.xx一般是局域网络

public static void main(String[] args) {
        try {

            InetAddress name = InetAddress.getByName("127.0.0.1");

            InetAddress host = InetAddress.getLocalHost();
            InetAddress byName = InetAddress.getByName("baidu.com");
            System.out.println(name);
            System.out.println(host);
            System.out.println(byName);
              //规范名称
            System.out.println(byName.getCanonicalHostName());
            //ip
            System.out.println(byName.getHostAddress());
            System.out.println(byName.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

端口

端口表示计算机上的一个程序的进程

  • 不同的进程有不同的端口号!用来区分软件!
  • 被规定0~65535
  • TCP,UDP 单个协议下端口号不能冲突
  • 端口分类
    • HTTP:80
    • HTTPS:443
    • FTP:21
    • Telent:23
    • 程序注册端口:2014~49151分配给用户或者程序
    • tomcat:8080
    • mysql:3306
    • Oracle:1521

netstat -ano #查看所有端口
netstat -ano|findstr "5900"#查看指定端口

通讯协议

协议:约定

网络通讯协议:速率,传输码率,代码结构,传输控制

TCP/IP协议簇

重要

  • TCP用户传输协议
  • UDP用户数据报协议
  • IP网络互连协议

TCP

客户端

  • 连接服务器Socket
  • 发送消息
public static void main(String[] args) throws IOException {
        Socket socket=null;
        OutputStream out=null;
        try {
            //知道服务器的IP地址
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            int port=8000;
            //创建一个socket连接
            socket = new Socket(ip,port);
            //发送消息IO流
            out = socket.getOutputStream();
            out.write("你好,萌萌".getBytes());


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
            socket.close();
        }
    }

服务器

  • 建立服务器的端口ServerSocket
  • 等待用户连接accept
  • 接受用户的消息
public static void main(String[] args) throws IOException {
        ServerSocket socket=null;
        Socket accept=null;
        InputStream input=null;
        ByteArrayOutputStream stream=null;
        try {
             socket=  new ServerSocket(8000);
            //等待客户端连接
             accept=socket.accept();
            //读取客户端的消息
          input = accept.getInputStream();
            //管道流
           stream = new ByteArrayOutputStream();
            byte[] bytes=new byte[1024];
            int len;
            while ((len=input.read(bytes))!=-1){
                    stream.write(bytes,0,len);
            }
            System.out.println(stream.toString());


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            stream.close();
            input.close();
            accept.close();
            socket.close();
            //关闭资源

        }
    }

文件上传

客户端

public static void main(String[] args) throws  Exception {
            //客户端
            //创建一个socket连接
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8000);
              //创建一个输出流
            OutputStream out = socket.getOutputStream();
               //文件流读取文件
            FileInputStream input = new FileInputStream(new File("C:\\Users\\xiaoming/Desktop/meng.txt"));

            //写出文件
            byte[] by = new byte[2048];
            int len;
            while ((len=input.read(by))!=-1){
                out.write(by,0,len);
            }
            //通知服务器传输完成
         socket.shutdownOutput();

            //确定服务器接受完毕,才能断开链接
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] by2 = new byte[2048];
        while ((len=inputStream.read(by2))!=-1){
            outputStream.write(by2,0,len);
        }
        System.out.println(outputStream.toString());

        //关闭资源
           input.close();
            out.close();
            socket.close();;

    }

服务端

public static void main(String[] args) throws IOException {
        //创建服务
        ServerSocket serverSocket = new ServerSocket(8000);
        //监听客户端的链接
        //阻塞式监听,会一直等待客户端连接
        Socket accept = serverSocket.accept();
        //获取输入流
        InputStream input = accept.getInputStream();
        //文件输出
        FileOutputStream out = new FileOutputStream(new File("receive.txt"));
        byte[] buffer = new byte[2048];

        int len;
        while ((len=input.read(buffer))!=-1){
               out.write(buffer,0,len);
        }
        //通知客户端我接受完毕了
        OutputStream os = accept.getOutputStream();
        os.write("我接受完毕了,可以断开链接了".getBytes());
        //关闭资源
        out.close();
        input.close();
        accept.close();
        serverSocket.close();

    }

UDP

发送端发送消息

public static void main(String[] args) throws Exception {
      //建立一个socket
        DatagramSocket socket = new DatagramSocket();
       //建立一个包
        String msg="你好";
        //发送给谁
        InetAddress localhost = InetAddress.getByName("127.0.0.1");

        //创建数据包
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,8000);

        //发送包
        socket.send(packet);
        //关闭流
        socket.close();
    }

接收端接受消息

public static void main(String[] args) throws Exception {
       //开放端口
        DatagramSocket socket = new DatagramSocket(8000);
        //接受数据包
        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(),0,packet.getLength()));
           //关闭连接
           socket.close();
    }
}

循环发送消息

public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket();
        InetSocketAddress address = new InetSocketAddress("127.0.0.1",8000);
        while (true){
            //准备数据控制台读取systeam.in
            Scanner sc=new Scanner(System.in);
            String st=sc.nextLine();
            byte[] buffer=st.getBytes();
            //添加数据,和要发送的地址
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length,address);

            socket.send(packet);
            if(st.equals("gg")){
                break;
            }
        }
        socket.close();
    }

循环接受消息

public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8000);

     while (true){
         //准备接收包裹
         byte[] bytes = new byte[1024];

         DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);

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

         byte[] bytes1=packet.getData();
         String sts=new String(bytes1,0,bytes1.length);
         System.out.println(sts);
         if(sts.equals("gg")){
             System.exit(0);
         }
      }
    }

多线程聊天

编写发送端send

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Scanner;

public class TalkSend implements Runnable{


        DatagramSocket socket=null;
        InetSocketAddress address=null;
        Scanner sc=null;
      private int fromport;
      private String toip;
      private int toport;
//        socket = new DatagramSocket();
//        address  = new InetSocketAddress("127.0.0.1",8000);


    public TalkSend(int fromport, String toip, int toport) throws Exception {
        this.fromport = fromport;
        this.toip = toip;
        this.toport = toport;
        this.socket=  new DatagramSocket(fromport);
        this.address=new InetSocketAddress(toip,toport);
        this.sc=new Scanner(System.in);

    }


    @Override
    public void run() {

        while (true){
            //准备数据控制台读取systeam.in

            String st=sc.nextLine();
            byte[] buffer=st.getBytes();
            //添加数据,和要发送的地址
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length,this.address);

            try {
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(st.equals("gg")){
                break;
            }
        }
        socket.close();
    }
}

编写接收端

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) throws Exception {
        this.port = port;
        this.msgfrom=msgfrom;
        this.socket = new DatagramSocket(this.port);
    }



    @Override
    public void run() {
        try {

            while (true){
                //准备接收包裹
                byte[] bytes = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);

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

                byte[] bytes1=packet.getData();
                String sts=new String(bytes1,0,bytes1.length);
                System.out.println(msgfrom+"接受消息"+sts);
                if(sts.equals("gg")){
                    System.exit(0);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

创建并启动接收和发送线程

public class Threadstudent {
    public static void main(String[] args) throws Exception {
        Thread thr1 = new Thread(new TalkSend(8000,"127.0.0.1",7000));
        Thread thread = new Thread(new TalkReceive(9000,"萌萌"));
        thr1.start();
        thread.start();
    }
}
public class TalkTeacher {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(new TalkSend(5000, "localhost", 9000));
        Thread thread1 = new Thread(new TalkReceive(7000, "学生"));
        thread.start();
        thread1.start();

    }
}

URL

统一资源定位符,定位互联网上的某一个资源

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

多线程下载网络资源

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class downThread implements Runnable {
   private String path="C:/Users/xiaoming/Desktop/";
   private long down=0;
    private String name="";

    Calendar calendar= Calendar.getInstance();
    SimpleDateFormat dateFormat= new SimpleDateFormat("hhmmss");
//System.out.println(dateFormat.format(calendar.getTime()));

    downThread(String path,long down) throws Exception {

       this.path=path;
       this.down=down;

    }
    @Override
    public void run() {
        this.name=Thread.currentThread().getName();
        while (down-->0){

            try {
                //下载地址
                URL url = new URL("http://www.jq22.com/jquery/jquery-3.4.1.zip");
                //链接到这个资源http
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                // 设置超时间为3秒
                connection.setConnectTimeout(3 * 1000);
                // 防止屏蔽程序抓取而返回403错误
                connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                InputStream input  = connection.getInputStream();
                FileOutputStream fos = new FileOutputStream(this.path+name+down+dateFormat.format(calendar.getTime())+"jquery-3.4.1.zip");

                System.out.println(input.read()+name+down);
                byte[] buffer = new byte[1024*124];
                int len;
                while ((len=input.read(buffer))!=-1){
                    //写出这个数据
                    fos.write(buffer,0,len);
                }
                //断开链接
                if(this.down==0){
                    fos.close();
                    input.close();
                    connection.disconnect();
                    break;
                }
                Thread.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
public class downTest {
    public static void main(String[] args) throws Exception {
        for (int i = 1; i <=500; i++) {
            Thread thread = new Thread(new downThread("C:\\Users\\xiaoming\\Desktop\\jqueryTest/", 10000));
            thread.setName("萌萌"+i);
            thread.start();
        }
        System.out.println("线程开启完毕");

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值