java中请给出UDP的DatagramSocket通信的例子?

3.UDP(数据报)协议的通信实例

马克-to-win:在UDP编程当中,技术上没有一个服务器和客户端的概念,即没有类似于TCP中的ServerSocket类,只有主动和被动之说, 客户端和服务器都用DatagramSocket(MyPORT)来绑定到一个端口,发送和接收dataPacket,它们是对等的双方。不过通常来讲, 先发送数据的被认为是客户端。in UDP, there is no concept of server or client, only active and passive, client and server both use new DatagramSocket(MyPORT) to bind to a port to use the port to send and receive the dataPacket, the counterpart which initially send the dataPacket is deemed as the client.  unlike the TCP protocol, there, there is really ServerSocket.
UDP通信主要有两个类,DatagramPacket是数据容器,它携带自己来自何处,以及打算去哪里的信息。DatagramSocket用来发送或接收DatagramPacket

DatagramPacket不仅需要包含正式的数据,也要包含网络地址以及端口号,以决定它的目的地。

 

例:2.3.1(客户端写,服务器端读)

服务器端:

import java.net.*;
import java.io.*;
import java.util.*;
public class TestMark_to_win {
    static final int MyPORT = 1711;
    public static void main(String[] args) throws IOException {
        byte[] bufreceive = new byte[1000];
        DatagramPacket packetreceive = new DatagramPacket(bufreceive,
                bufreceive.length);//测试结果bufreceive.length是1000
        DatagramSocket socket;
        socket = new DatagramSocket(MyPORT);
        // Block until a datagram appears:
        socket.receive(packetreceive);
        String stringreceive = new String(packetreceive.getData(), 0,
                packetreceive.getLength());
        System.out.println(stringreceive);
        socket.close();
    }
}

客户端程序:
import java.net.*;
import java.io.*;
import java.util.*;
public class Test {
    static final int MyPORT = 1710;
    static final int SERVERPORT = 1711;
    public static void main(String[] args) throws IOException {
        byte[] bufsend = new byte[1000];
        DatagramSocket client;
        InetAddress destination = InetAddress.getByName("localhost");
        client = new DatagramSocket(MyPORT);
        bufsend = "java study".getBytes();// string encode to a byte array
        DatagramPacket sendpacket = new DatagramPacket(bufsend, bufsend.length,
                destination, SERVERPORT);
        client.send(sendpacket);
        client.close();
    }
}

更多请见:https://blog.csdn.net/qq_44639795/article/details/102079039

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mark_to_win

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值