Java 网络编程

本文介绍了网络编程的基本概念,包括IP、端口和协议的重要性。详细讲解了UDP和TCP两种协议的通信过程,提供了发送端和接收端的Java实现示例。UDP是一种无连接、高效但不可靠的协议,而TCP则是面向连接、可靠但效率较低的协议。示例代码展示了如何使用DatagramSocket和Socket进行数据传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是网络编程?

百度百科:网络编程从大的方面说就是对信息的发送到接收,中间传输为物理线路的作用。网络编程最主要的工作就是在发送端把信息通过规定好的协议进行组装包,在接收端按照规定好的协议把包进行解析,从而提取出对应的信息,达到通信的目的。

网络编程三要素

  • IP:用于找到地址互相通信
  • 端口:用于找到我们的应用程序,例如:微信发送的数据也只能微信接收
  • 协议:用于通信传输数据的协议,常见的协议有TCP和UDP

UDP通信

用户数据包协议,发送端只管发数据,不管接收端是否能够接收到,但效率较高,常用于不安全但需要传输快的数据传输

发送端发送数据步骤:

  • 创建发送端对象DatagramSocket()
  • 将数据打包
  • 发送数据
  • 关闭发送端资源
//创建发送端对象
DatagramSocket ds=new DatagramSocket();

byte[] b="886".getBytes();
//发送端必须指定参数:数据、数据长度、到那个主机,哪个端口
DatagramPacket dp=new DatagramPacket(b,b.length,InetAddress.getByName(null),8080);

//发送数据
ds.send(dp)

//关闭资源
ds.close()

接收端接收数据步骤:

  • 创建接收端对象DatagramSocket(port)
  • 接收数据
  • 解析数据包
  • 关闭资源
//创建接收端对象
DatagramSocket ds=new DatagramSocket(8080);

//创建一个包来接收数据
byte[] b=new byte[1024];
DatagramPacket dp=new DatagramPacket(b,b.length);

//接收数据
ds.receive(dp);

//解析数据包
byte[] data=dp.getData();
String s=new String(data, 0, dp.getLength());
System.out.println(s);

从键盘输入的网络传输
发送端

//发送端
public class A {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds=new DatagramSocket();

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line=br.readLine())!=null){
            if(line.equals("886")){
                DatagramPacket dp=new DatagramPacket("886".getBytes(),"886".getBytes().length,InetAddress.getByName(null),8080);
                ds.send(dp);

                ds.close();
                System.out.println("发送结束");
                break;
            }
            DatagramPacket dp=new DatagramPacket(line.getBytes(),line.getBytes().length,InetAddress.getByName(null),8080);
            ds.send(dp);
        }
    }
}

接收端

//接收端
public class B {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException, InstantiationException {
        DatagramSocket ds=new DatagramSocket(8080);

        while(true){
            byte[] b=new byte[1024];
            DatagramPacket dp=new DatagramPacket(b,b.length);

            ds.receive(dp);

            byte[] data=dp.getData();
            if(new String(data, 0, dp.getLength()).equals("886")){
                System.out.println("接收结束");
                break;
            }
            System.out.println(new String(data, 0, dp.getLength()));
        }

        ds.close();
    }
}

TCP通信

传输控制协议,在通信两端各建立一个Socket对象,连接前会有一个三次握手的过程,并且结束会有一个四次断开,但效率低,适用于安全的数据传输。
发送端发送数据步骤:

  • 建立发送端Socket对象
  • 获取输出流
  • 将数据发送
  • 关闭发送端对象

需要注意的是,发送端想要发送数据必须先开启接收端,因为有三次握手

//发送端
public class A {
    public static void main(String[] args) throws IOException {
        Socket ss=new Socket("127.0.0.1",8080);

        OutputStream outputStream = ss.getOutputStream();

        outputStream.write("hello".getBytes());

        ss.close();
    }
}

接收端接收数据步骤:

  • 建立接收端ServerSocket对象
  • 监听发送端
  • 获取输入流
  • 接收数据
  • 关闭接收端对象
public class B {
    public static void main(String[] args) throws IOException {
        ServerSocket ss=new ServerSocket(8080);

        Socket sss = ss.accept();

        InputStream inputStream = sss.getInputStream();

        byte[] b=new byte[1024];
        int len=inputStream.read(b);
        String str=new String(b,0,len);
        System.out.println(str);
    }
}

将文件从一台主机发送到另一台主机
发送端

public class A {
    public static void main(String[] args) throws IOException {
        Socket ss=new Socket("127.0.0.1",8080);

        BufferedReader br=new BufferedReader(new FileReader("data.txt"));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ss.getOutputStream()));

        String line;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.flush();
            bw.newLine();
        }

        ss.close();
    }
}

接收端

public class B {
    public static void main(String[] args) throws IOException {
        ServerSocket ss=new ServerSocket(8080);

        Socket sss = ss.accept();

        BufferedReader br=new BufferedReader(new InputStreamReader(sss.getInputStream()));
        BufferedWriter bw=new BufferedWriter(new FileWriter("date.txt"));

        String line;
        while((line=br.readLine())!=null){
            bw.write(line);
            bw.flush();
            bw.newLine();
        }

        ss.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值