最近项目需要用到UDP传输报文数据,特意花时间来学习了一下。话不多说,代码为上。
- 首先是通用bean的设计:
/** * @Author WQ * @Date 2018/11/20 - 9:42 * @Description 通用Bean */ public class DatagramBean { protected byte[] buffer;//用来封装通讯字符串 protected String content;//通讯内容 protected InetAddress inetAddress;//描述通讯地址 protected int clientPort; protected int serverPort; public DatagramBean() throws Exception { buffer = new byte[1024]; content = ""; //初始化客户端和服务端端口 clientPort = 1985; serverPort = 1986; //inetAddress = InetAddress.getByName("localhost"); inetAddress = InetAddress.getLocalHost(); } public byte[] getBuffer() { return buffer; } public void setBuffer(byte[] buffer) { this.buffer = buffer; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public InetAddress getInetAddress() { return inetAddress; } public void setInetAddress(InetAddress inetAddress) { this.inetAddress = inetAddress; } public int getClientPort() { return clientPort; } public void setClientPort(int clientPort) { this.clientPort = clientPort; } public int getServerPort() { return serverPort; } public void setServerPort(int serverPort) { this.serverPort = serverPort; } } |
2.服务端通用bean
* @Author WQ * @Date 2018/11/20 - 9:41 * @Description 服务器端通用类 */ public class DatagramServerBean extends DatagramBean { //数据包套接字:相当于码头,专门处理通信数据及进行数据转发设置的 private DatagramSocket serverDatagramSocket; private DatagramPacket serverDatagramPacket; public DatagramServerBean() throws Exception { super(); serverDatagramSocket = new DatagramSocket(serverPort); } public void listenClient() throws Exception { while (true) { //初始化DatagramPacket //数据报包:类似于集装箱,用来存储所有的数据信息 serverDatagramPacket = new DatagramPacket(buffer, buffer.length); //接受客户端消息,并通过DatagramPacket参数返回 serverDatagramSocket.receive(serverDatagramPacket); content = new String(serverDatagramPacket.getData(), 0, serverDatagramPacket.getLength()); send(content); print(); } } /** * 向客户端发送数据 * * @param content */ private void send(String content) { DatagramPacket datagramPacket = new DatagramPacket(buffer, 0, buffer.length, serverDatagramPacket.getAddress(), serverDatagramPacket.getPort()); datagramPacket.setData(("服务端响应 : " + content).getBytes()); try { serverDatagramSocket.send(datagramPacket); } catch (IOException e) { e.printStackTrace(); } } private void print() { System.out.println(content); } } |
3.客户端通用bean
* @Author WQ * @Date 2018/11/20 - 9:28 * @Description 客户端通用bean */ public class DatagramClientBean extends DatagramBean { private DatagramSocket clientDatagramSocket; public DatagramClientBean() throws Exception { super(); clientDatagramSocket= new DatagramSocket(clientPort); } /** * 发送数据到服务端 * * @throws IOException */ public void sendToServer() throws IOException { buffer = content.getBytes();//数据都是已字节数据进行发送的,因此需要将数据进行转换 clientDatagramSocket.send(new DatagramPacket( buffer, content.getBytes().length, //发送数据的长度 inetAddress, serverPort)); } public String receive() { buffer = new byte[1024 * 1024 * 64];//数据都是已字节数据进行发送的,因此需要将数据进行转换 DatagramPacket dpr = new DatagramPacket(buffer, buffer.length); String info = ""; try { clientDatagramSocket.receive(dpr); info = new String(dpr.getData(), 0, dpr.getLength(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } return info; } } |
4.服务端启动类
* @Author WQ * @Date 2018/11/20 - 9:51 * @Description 服务端启动类 */ public class Server { public static void main(String[] args) throws Exception { System.out.println("服务端启动"); //初始化ServerBean DatagramServerBean server = new DatagramServerBean(); server.listenClient(); } } |
5.客户端启动类
* @Author WQ * @Date 2018/11/20 - 9:30 * @Description */ public class Client implements Runnable { public static String content; public static DatagramClientBean client; @Override public void run() { try { client.setContent(content); client.sendToServer(); } catch (IOException e) { System.err.println(e.getMessage()); } } public static void main(String[] args) throws Exception { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); client = new DatagramClientBean(); System.out.println("启动客户端"); /*while (true) { content = bufferedReader.readLine();//接收用户输入 if (content == null || content.equalsIgnoreCase("end") || content.equalsIgnoreCase("")) { break; } new Thread(new Client()).start();//开启新线程,发送消息 //接收服务端反馈 String receiveMessage = client.receive(); System.out.println(receiveMessage); }*/ //---------------------------xml------------------------------------------ //得到 DOM 解析器的工厂实例 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //从 DOM 工厂获得 DOM 解析器 DocumentBuilder builder = factory.newDocumentBuilder(); //创建Document Document document = builder.newDocument(); //创建Element Element root = document.createElement("COMMAND_INFO"); //第一个节点--场站名称 Element r1 = document.createElement("AREA_NAME"); r1.setTextContent("A站"); root.appendChild(r1); //第二个节点--通道名称 Element r2 = document.createElement("CHNL_NAME"); r2.setTextContent("A通道"); root.appendChild(r2); //第三个节点--非监控端IP Element r3 = document.createElement("MONITOR_IP"); r3.setTextContent("192.168.1.11"); root.appendChild(r3); //第四个节点--非监控端端口 Element r4 = document.createElement("MONITOR_PORT"); r4.setTextContent("6666"); root.appendChild(r4); //第五个节点--用户信息 Element r5 = document.createElement("USER_INFO"); //第五个节点的第一个子节点-----用户登录名称 Element r51 = document.createElement("USER_ID"); r51.setTextContent("Jack"); r5.appendChild(r51); //第五个节点的第二个子节点-----密码 Element r52 = document.createElement("PSW"); r52.setTextContent("123456"); r5.appendChild(r52); //第五个节点的第三个子节点-----软KEY值 Element r53 = document.createElement("KEY"); r53.setTextContent("Superman"); r5.appendChild(r53); //第五个节点的第四个子节点-----登录时间值 Element r54 = document.createElement("TIMESTAMP"); r54.setTextContent(new SimpleDateFormat("yyyy-MM-dd").format(new Date())); r5.appendChild(r54); //讲r5添加到root节点 root.appendChild(r5); //将root节点添加到Document document.appendChild(root); //将构造好的Document转换为String并发送给服务端 content = doc2String(document); new Thread(new Client()).start();//开启新线程,发送消息 //接收服务端反馈 String receiveMessage = client.receive(); System.out.println(receiveMessage); //---------------------------xml------------------------------------------ } /** * Document 转换为 String * * @param doc XML的Document对象 * @return String */ public static String doc2String(Document doc) { try { //XML转字符串 TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); //t.setOutputProperty("encoding","GB23121");//解决中文问题,试过用GBK不行 t.setOutputProperty("encoding", "UTF-8"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); t.transform(new DOMSource(doc), new StreamResult(bos)); String xmlStr = bos.toString(); return xmlStr; } catch (Exception e) { e.printStackTrace(); return null; } } } |
如果能帮到大家,我很开心,谢谢各位大佬,有什么问题大家 一些讨论,共同进步。