博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UDP编程
阅读量:5982 次
发布时间:2019-06-20

本文共 2129 字,大约阅读时间需要 7 分钟。

Server.java

package com.zby;import java.net.DatagramPacket;import java.net.DatagramSocket;public class Server {    private static boolean running = true;    public static void main(String[] args) throws Exception {        DatagramSocket server = new DatagramSocket(8888);        byte[] buffer = new byte[1024];        DatagramPacket requestPacket = new DatagramPacket(buffer, buffer.length);        while (running) {            server.receive(requestPacket);            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());            System.out.println("request:" + request);            System.out.println("InetAddress:" + requestPacket.getAddress());            System.out.println("port:" + requestPacket.getPort());            System.out.println();            String response = "Hello,Client!";            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,                    requestPacket.getAddress(), requestPacket.getPort());            server.send(responsePacket);        }        server.close();    }}

Client.java

package com.zby;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class Client {    public static void main(String[] args) throws Exception {        DatagramSocket client = new DatagramSocket(7777);        String request = "Hello,Server!";        DatagramPacket datagramPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,                InetAddress.getLocalHost(), 8888);        client.send(datagramPacket);        byte[] buffer = new byte[1024];        DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length);        client.receive(responsePacket);        String response = new String(responsePacket.getData(), 0, responsePacket.getLength());        System.out.println("response:" + response);        System.out.println("InetAddress:" + responsePacket.getAddress());        System.out.println("port:" + responsePacket.getPort());        System.out.println();        client.close();    }}

 

转载于:https://www.cnblogs.com/zby9527/p/7651251.html

你可能感兴趣的文章
中大型网站技术架构演变过程
查看>>
ARTS训练第三周
查看>>
vue中v-for循环如何将变量带入class的属性名中
查看>>
phpstorm xdebug remote配置
查看>>
引用与指针的区别
查看>>
pygtk笔记--2.1:布局容器,VBox、Hbox、Alignment
查看>>
dtree.js树的使用
查看>>
Springboot2.1.3 + redis 实现 cache序列化乱码问题
查看>>
线程什么时候需要同步,什么时候不需要同步?
查看>>
Struts2 自定义拦截器(方法拦截器)
查看>>
Linux服务器的那些性能参数指标
查看>>
BZOJ 2302: [HAOI2011]Problem c [DP 组合计数]
查看>>
c++ 11开始语言本身和标准库支持并发编程
查看>>
.NET Core 之 MSBuild 介绍
查看>>
iOS:即时通讯之<了解篇 SocKet>
查看>>
《JavaScript高级程序设计》读书笔记(十):本地对象Date
查看>>
linux中fork()函数详解
查看>>
从1G到5G,46年屏幕变迁下,富士康、苹果、三星、华为的浴火重生路 ...
查看>>
用flash测试你的ircd
查看>>
白话红黑树系列之二——红黑树的构建
查看>>