首页 > 编程语言 >网络编程Day02

网络编程Day02

时间:2024-09-29 20:24:03浏览次数:1  
标签:java socket Day02 编程 网络 new close import net

通信协议

网络通信协议:速率、传输码率、代码结构、传输控制...

问题:非常的复杂

分层:大事化小

TCP/IP协议簇:实际上是一组协议

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

TCP UDP对比

  • TCP:打电话

    • 连接,稳定

    • 三次握手,四次分手

      最少需要三次,保证稳定连接

      最少需要四次,保证连接断开

    • 客户端、服务端

    • 传输完成,释放连接,效率低

  • UDP:发短信

    • 不连接,不稳定
    • 客户端、服务端没有明确的界限
    • 不管有没有准备好,都可以发送

TCP

客户端

  1. 连接服务器Socket
  2. 发送消息
package com.dongfang.ip.lesson02;

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

        Socket socket = null;
        OutputStream os = null;

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

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (os != null) {
                try{
                    os.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }

            if (socket != null) {
                try{
                    socket.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

服务器

  1. 建立服务器端口ServerSocket
  2. 等待用户的连接accept
  3. 接收用户的消息
package com.dongfang.ip.lesson02;

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) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;

        try {
            //1.得有一个地址
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接过来
            socket = serverSocket.accept();//同一个socket
            //3.读取客户端的消息
            is = socket.getInputStream();

            /*
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1){
                String msg = new String(buffer, 0, len);
                System.out.println(msg);
            }
            */

            //管道流
            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){
                try {
                    baos.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.dongfang.ip.lesson02;

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

public class TCPClientDemo02 {
    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("food_big.jpg"));
        //4.写出文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            os.write(buffer,0,len);
        }

        //通知服务器已经传输完毕
        socket.shutdownOutput();

        //确定服务器接收完毕才能够断开连接
        InputStream is = socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len2;
        while ((len2 = is.read(buffer2)) != -1) {
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());

        //5.关闭资源
        baos.close();
        fis.close();
        os.close();
        is.close();
        socket.close();
    }
}

服务器端

package com.dongfang.ip.lesson02;

import java.io.File;
import java.io.FileOutputStream;
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(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());

        //5.关闭资源
        fos.close();
        is.close();
        serverSocket.close();
        socket.close();
    }
}

Tomcat

服务端

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

客户端

  • 自定义 C
  • 浏览器 B

UDP

不用连接,但是需要知道对方的地址

发送端

package com.dongfang.ip.lesson03;

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 = "Hello World";
        //发送给谁
        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.dongfang.ip.lesson03;

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

//还是要等待客户端的连接
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(),0,packet.getLength()));
        //关闭连接
        socket.close();
    }
}

UDP聊天

循环发送消息

package com.dongfang.ip.chat;

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

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

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

        socket.send(packet);

        socket.close();
    }
}

循环接收消息

import java.net.DatagramSocket;

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

            //断开连接  bye
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, packet.getLength());
            System.out.println(receiveData);
            if (receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

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

URL

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

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

package com.dongfang.ip.lesson04;

import java.net.MalformedURLException;
import java.net.URL;

public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=dongfangyulv&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());//参数
    }
}
package com.dongfang.ip.lesson04;

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/dongfangyulv/SecurityFile.txt");

        //连接到这个资源  HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("SecurityFile.txt");

        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != 1){
            fos.write(buffer,0,len);//写出这个数据
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接
    }
}

标签:java,socket,Day02,编程,网络,new,close,import,net
From: https://www.cnblogs.com/dongfangyulv/p/18440685

相关文章

  • shell编程五
    10.循环10.1循环概述循环类型说明for循环最常用的循环,2种格式while循环当型循环while可以加入条件,死循环,读取文件dountil循环直到循环极少用10.2for循环10.2.1最常用的for循环格式#最常用的一种for变量in候补清单(列表)do命令doneforn......
  • Python 面向对象编程基础
    面向对象编程(Object-OrientedProgramming,OOP)是一种编程范式,它将数据和操作数据的方法(函数)组合在一起,形成一个“对象”。Python是一种支持面向对象编程的语言,本文将介绍Python中面向对象编程的基础知识。类与对象在面向对象编程中,类(Class)是创建对象的蓝图或模板。它定......
  • 实验1_C语言输入输出和简单程序应用编程
    task.1//打印一个字符小人#include<stdio.h>intmain(){printf("O\n");printf("<H>\n");printf("II\n");return0;}  task.1-1&1-2#include<stdio.h>intmain(){printf(&qu......
  • 关于开发板与虚拟机网络不通问题排查
    文章目录一、网络连接二、排查过程1.首先检查Windows和开发板的WIFI模块是否处于同一个局域网2.检查端口转发配置是否正确3.查看防火墙是否关闭一、网络连接开发板(客户端)---wifi模块---无线路由器---Windows主机---NAT模式---Ubuntu虚拟机(服务器)开发板通过WIF......
  • 1.1.5 计算机网络的性能指标(下)
    时延:指数据从网络的一端传送到另一端所需的时间。有时候也称为延迟或迟延。总时延=发送时延+传播时延+处理时延+排队时延发送时延:又名传输时延,节点将数据推向信道所花的时间 =数据长度/发送速率传播时延:电磁波在信道中传播一定距离所花的时间信道长度/电磁波在信道中......
  • 【蓝桥杯】“萌新首秀”全国高校新生编程排位赛2
    一、Hello Lanqiao题目HelloLanqiao 代码#include<iostream>usingnamespacestd;intmain(){cout<<"HelloLanqiao";return0;}二、懒羊羊字符串题目懒羊羊字符串  题目分析1.使用一个for循环去一个一个判断输入的n行字符串2.使用一个if判断,判断......
  • Pytorch学习笔记--搭建神经网络以及Sequential的使用
    首先,搭建一个如下图所示的神经网络: 分析图片,inputs输入图片的inchannels=3,尺寸是32*32,经过kernel_size=5的卷积操作后out_channels=32,尺寸32*32,套用下方公式可算出padding=2(默认dilation=1,stride=1):self.conv1=Conv2d(3,32,5,padding=2)  之后再进行池化操作Max-poolin......
  • C++的并发编程历史
    多线程环境并非所有的语言都提供了多线程的环境。即便是C++语言,直到C++11标准之前,也是没有多线程支持的。在这种情况下,Linux/Unix平台下的开发者通常会使用POSIXThreads,Windows上的开发者也会有相应的接口。但很明显,这些API都只针对特定的操作系统平台,可移植性较差。如果要同......
  • HarmonyOs DevEco Studio小技巧24--异步编程(Promises、async/await)
    异步编程:调用后耗时,不阻塞代码继续执行,将来完成后,触发回调函数传递结果异步编程的范畴:网络请求(如使用 fetch 或 XMLHttpRequest 发送HTTP请求获取数据)。文件读写操作(读取或写入本地文件)。数据库操作(查询、插入、更新、删除数据)。定时器函数(如 setTimeout 和 setInt......
  • Flink(八)状态编程
    Flink中的状态状态:在处理流数据时,算子(Operators)所维护的随着时间变化而持续或在特定时间点被查询的数据无状态的算子任务:只需要观察每个独立事件,根据当前输入的数据直接转换输出结果有状态的算子任务:除当前数据外,还需要一些其他数据来得到计算结果状态的分类算子状态(Operat......