电脑之家 - 专业计算机基础知识与电脑技术学习网站
分类导航

路由器|交换机|网络协议|网络知识|

服务器之家 - 电脑之家 - 网络技术 - 网络协议 - UDP简单服务端客户端代码示例

UDP简单服务端客户端代码示例

2021-07-19 01:05cuisuqiang 网络协议

这篇文章主要介绍了UDP简单服务端客户端代码示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

UDP的理论不再多说,我这里直接给出一个关于UDP的HelloWorld程序,代码明了,希望对刚入门的学生有所帮助!

当然,实际上,在这块我也刚入门!

首先写服务端代码,服务端邦定本地的IP和端口来监听访问:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package udp;
 
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
 
/**
 * UDP服务类
 */
public class UdpServerSocket {
    
    private byte[] buffer = new byte[1024];
    private static DatagramSocket ds = null;
    private DatagramPacket packet = null;
    private InetSocketAddress socketAddress = null;
    
    /**
     * 测试方法
     */
    public static void main(String[] args) throws Exception {
        String serverHost = "127.0.0.1";
        int serverPort = 3344;
        UdpServerSocket udpServerSocket = new UdpServerSocket(serverHost,
                serverPort);
        while (true) {
            udpServerSocket.receive();
            udpServerSocket.response("你好,吃了吗!");
        }      
    }
 
    /**
     * 构造函数,绑定主机和端口
     */
    public UdpServerSocket(String host, int port) throws Exception {
        socketAddress = new InetSocketAddress(host, port);
        ds = new DatagramSocket(socketAddress);
        System.out.println("服务端启动!");
    }
 
    /**
     * 接收数据包,该方法会造成线程阻塞
     */
    public final String receive() throws IOException {
        packet = new DatagramPacket(buffer, buffer.length);
        ds.receive(packet);
        String info = new String(packet.getData(), 0, packet.getLength());
        System.out.println("接收信息:" + info);
        return info;
    }
 
    /**
     * 将响应包发送给请求端
     */
    public final void response(String info) throws IOException {
        System.out.println("客户端地址 : " + packet.getAddress().getHostAddress()
                + ",端口:" + packet.getPort());
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length, packet
                .getAddress(), packet.getPort());
        dp.setData(info.getBytes());
        ds.send(dp);
    }
}

运行后提示服务端运行成功,程序开始监听端口,接收方法堵塞,当有访问时才会向下进行!

我们写客户端进行访问,看到网上的例子都是直接创建了 DatagramSocket 对象,而其实自己都不知道自己使用的端口是那个,这里我创建时会指定自己邦定的端口,其实很简单,就是初始化该对象时传递一个端口参数。

这里你访问客户端时客户端会打印你的IP和端口!

看一看客户端代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package udp;
 
import java.io.*;
import java.net.*;
 
/**
 * UDP客户端程序,用于对服务端发送数据,并接收服务端的回应信息
 */
public class UdpClientSocket {
    private byte[] buffer = new byte[1024];
 
    private static DatagramSocket ds = null;
    
    /**
     * 测试客户端发包和接收回应信息的方法
     */
    public static void main(String[] args) throws Exception {
        UdpClientSocket client = new UdpClientSocket();
        String serverHost = "127.0.0.1";
        int serverPort = 3344;
        client.send(serverHost, serverPort, ("你好,亲爱的!").getBytes());
        byte[] bt = client.receive();
        System.out.println("服务端回应数据:" + new String(bt));
        // 关闭连接
        try {
            ds.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
 
    /**
     * 构造函数,创建UDP客户端
     */
    public UdpClientSocket() throws Exception {
        ds = new DatagramSocket(8899); // 邦定本地端口作为客户端
    }
    
    /**
     * 向指定的服务端发送数据信息
     */
    public final void send(final String host, final int port,
            final byte[] bytes) throws IOException {
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(host), port);
        ds.send(dp);
    }
 
    /**
     * 接收从指定的服务端发回的数据
     */
    public final byte[] receive()
            throws Exception {
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
        ds.receive(dp);    
        byte[] data = new byte[dp.getLength()];
        System.arraycopy(dp.getData(), 0, data, 0, dp.getLength());    
        return data;
    }
}

直接运行程序看效果!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.iteye.com/blog/cuisuqiang-1543190

延伸 · 阅读

精彩推荐