Vert.x实战六:TCP客户端之间以功能名通过服务端转接通信

news/2024/5/17 18:20:33 标签: Vert.x, TCP, Java

Vert.x系列:
Vert.x介绍:https://blog.csdn.net/haoranhaoshi/article/details/89279096
Vert.x实战一:Vert.x通过Http发布数据:https://blog.csdn.net/haoranhaoshi/article/details/89284847
Vert.x实战二:TCP通信:https://blog.csdn.net/haoranhaoshi/article/details/89296522
Vert.x实战三:TCP客户端之间以角色通过服务端转接通信:https://mp.csdn.net/postedit/89296606
Vert.x实战四:TCP客户端之间以角色和同一角色连接顺序通过服务端转接通信:https://blog.csdn.net/haoranhaoshi/article/details/89296665
Vert.x实战五:TCP客户端之间以ID通过服务端转接通信:https://blog.csdn.net/haoranhaoshi/article/details/89296754
Vert.x实战六:TCP客户端之间以功能名通过服务端转接通信:https://blog.csdn.net/haoranhaoshi/article/details/89296841
Vert.x实战七:TCP设置超时断开:https://blog.csdn.net/haoranhaoshi/article/details/89296986
Vert.xTCP服务端和客户端配置:https://blog.csdn.net/haoranhaoshi/article/details/89297022
Vert.x的Http和TCP实战代码下载:https://download.csdn.net/download/haoranhaoshi/11114611

本篇:TCP发送功能名称,负责执行功能的客户端收到消息,功能和负责执行功能的客户端ID可配置。

package VertxTCPFunctionTest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetSocket;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VertxTCPServer extends AbstractVerticle {
    private Map<String, NetSocket> idMap = new HashMap<>();
    private Map<String, List<String>> functionMap = FunctionReader.getFunctionData();

    @Override
    public void start() {
        // 创建TCP服务器
        NetServer server = vertx.createNetServer();

        // 处理连接请求
        server.connectHandler(socket -> {
            // 读写消息
            socket.handler(buffer -> {
                // 在这里应该解析报文,封装为协议对象,并找到响应的处理类,得到处理结果,并响应
                String message = buffer.toString();
                System.out.println("接收到的数据为:" + message);
                JSONObject jsonObject = JSON.parseObject(message);
                String connectClientID = jsonObject.getString("id");
                if (connectClientID != null) {
                    if(idMap.get(connectClientID) != null){
                        socket.write("id已经存在,当前id有:" + idMap.keySet().toString());
                    }else{
                        idMap.put(connectClientID, socket);
                        System.out.println("客户端" + connectClientID + "已加入,当前客户端id有:" + idMap.keySet().toString());
                    }
                } else{
                    String messageHead = jsonObject.getString("messageHead");
                    String messageBody = jsonObject.getString("messageBody");
                    if(messageHead != null){
                        List<String> idList = functionMap.get(messageHead);
                        JSONObject responseJsonObject = new JSONObject();
                        JSONObject messageJsonObject = new JSONObject();
                        JSONArray infoJsonArray = new JSONArray();
                        if(idList == null){
                            infoJsonArray.add("未配置功能" + messageHead);
                            responseJsonObject.put("info", infoJsonArray);
                            socket.write(responseJsonObject.toJSONString());
                        }else{
                            for(String functionID : idList){
                                NetSocket netSocket = idMap.get(functionID);
                                if(netSocket == null){
                                    String infoPart =  "负责接收功能" + messageHead + "通知的客户端" + functionID + "不在线";
                                    infoJsonArray.add(infoPart);
                                }else{
                                    if(netSocket == socket){
                                        messageJsonObject.put("message", messageBody);
                                    }else{
                                        JSONObject otherMessageJsonObject = new JSONObject();
                                        otherMessageJsonObject.put("message", messageBody);
                                        netSocket.write(otherMessageJsonObject.toString());
                                    }

                                    String infoPart = "已发送" + messageHead + "给客户端" + functionID;
                                    infoJsonArray.add(infoPart);
                                }
                            }

                            responseJsonObject.put("info", infoJsonArray);
                            if(messageJsonObject != null){
                                responseJsonObject.put("message", messageJsonObject);
                            }

                            socket.write(responseJsonObject.toJSONString());
                        }

                    }
                }
            });

            // 监听客户端的退出连接
            socket.closeHandler(close -> {
                for(Map.Entry mapEntry : idMap.entrySet()){
                    if(mapEntry.getValue() == socket){
                        String id = (String)mapEntry.getKey();
                        idMap.remove(id);
                        System.out.println("客户端" + id +"退出连接,当前客户端id有:" + idMap.keySet().toString());
                    }
                }
            });
        });

        // 监听端口
        server.listen(33323, res -> {
            if (res.succeeded()) {
                System.out.println("服务器启动成功");
            }
        });
    }

    public static void main(String[] args) {
        Vertx.vertx().deployVerticle(new VertxTCPServer());
    }
}
package VertxTCPFunctionTest;

import com.alibaba.fastjson.JSONObject;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetSocket;

import java.util.Scanner;

public class VertxTCPClient extends AbstractVerticle {
    private static String ID = "2";
    private static NetSocket netSocket;

    @Override
    public void start() {
        // 创建一个TCP客户端
        NetClient client = vertx.createNetClient();

        // 连接服务器
        client.connect(33323, "localhost", conn -> {
            if (conn.succeeded()) {
                System.out.println("客户端" + ID + "连接服务端成功");
                netSocket = conn.result();
                // 向服务器写数据
                JSONObject idJsonObject = new JSONObject();
                idJsonObject.put("id", ID);
                netSocket.write(Buffer.buffer(idJsonObject.toJSONString()));

                // 读取服务器的响应数据
                netSocket.handler(buffer -> System.out.println("接收到的数据为:" + buffer.toString()));
            } else {
                System.out.println("连接服务器异常");
            }
        });
    }

    public static void main(String[] args) {
        Vertx.vertx().deployVerticle(new VertxTCPClient());
        // 向服务端发送消息
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String message = scanner.next();
            JSONObject messageJsonObject = new JSONObject();
            messageJsonObject.put("messageHead", message.split(":")[0]);
            messageJsonObject.put("messageBody", message.split(":")[1]);
            netSocket.write(Buffer.buffer(messageJsonObject.toJSONString()));
        }
    }
}
package VertxTCPFunctionTest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FunctionReader {
    public static void main(String[] args){
        getFunctionData();
    }

    public static Map<String, List<String>> getFunctionData(){
        Document document;
        try {
            SAXReader reader = new SAXReader();
            String filePath = new File("").getAbsolutePath() + "/src/VertxTCPFunctionTest/function.xml";
            File file = new File(filePath);
            if(file == null){
                return null;
            }

            document = reader.read(file);

            Map<String, List<String>> functionMap = new HashMap<>();
            for(Element functionElement : document.getRootElement().elements("Function")){
                String functionName = functionElement.attributeValue("functionName");
                List<String> idList = functionMap.get(functionName);
                if(idList == null){
                    idList = new ArrayList<>();
                }

                for(Element idElement : functionElement.elements("ID")){
                    String id = idElement.getTextTrim();
                    if(!idList.contains(id)){
                        idList.add(id);
                    }
                }

                functionMap.put(functionName, idList);
            }

            return functionMap;
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
    }
}

 function.xml:

<Functions>
    <Function functionName = "A">
        <ID>1</ID>
        <ID>2</ID>
    </Function>
    <Function functionName = "B">
        <ID>1</ID>
        <ID>3</ID>
        <ID>4</ID>
    </Function>
</Functions>

客户端ID可以在启动参数中配置,打包后可以在启动文件(bat文件)中配置,格式为ID=客户端ID。

Client的main方法中加入:

        for(String arg : args){
            if(arg.indexOf("ID=") != -1){
                ID = arg.split("=")[1];
            }
        }

 


http://www.niftyadmin.cn/n/752608.html

相关文章

【BFS】【迭代】【Java】迷宫问题

定义一个二维数组&#xff1a; intmaze[5][5]{ 0,1,0,0,0, 0,1,0,1,0, 0,0,0,0,0, 0,1,1,1,0, 0,0,0,1,0, }; 它表示一个迷宫&#xff0c;其中的1表示墙壁&#xff0c;0表示可以走的路&#xff0c;只能横着走或竖着走&#xff0c;不能斜着走&#xff0c;要求编程序找出从左上角…

Vert.x实战七:TCP设置超时断开

Vert.x系列&#xff1a; Vert.x介绍&#xff1a;https://blog.csdn.net/haoranhaoshi/article/details/89279096 Vert.x实战一&#xff1a;Vert.x通过Http发布数据&#xff1a;https://blog.csdn.net/haoranhaoshi/article/details/89284847 Vert.x实战二&#xff1a;TCP通信&a…

【DFS】【递归】【Java】Leetcode 733. 图像渲染

有一幅以二维整数数组表示的图画&#xff0c;每一个整数表示该图画的像素值大小&#xff0c;数值在 0 到 65535 之间。 给你一个坐标 (sr, sc) 表示图像渲染开始的像素值&#xff08;行 &#xff0c;列&#xff09;和一个新的颜色值 newColor&#xff0c;让你重新上色这幅图像…

wpf 禁用window的systemmenu

private IntPtr WidProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled){if (msg 0x112){if (wParam.ToInt32() 0xF093)//单击打开菜单handled true;if (wParam.ToInt32() 0xF100) //键盘打开菜单 handled true;}if (msg 0xa4){if (wParam.ToIn…

Vert.x的TCP服务端和客户端配置

Vert.x系列&#xff1a; Vert.x介绍&#xff1a;https://blog.csdn.net/haoranhaoshi/article/details/89279096 Vert.x实战一&#xff1a;Vert.x通过Http发布数据&#xff1a;https://blog.csdn.net/haoranhaoshi/article/details/89284847 Vert.x实战二&#xff1a;TCP通信&a…

【python】【爬虫】爬取Fate Grand Order wiki所有英灵礼装图鉴

import requests from lxml import etreefor i in range(1,895): url0"https://fgowiki.com/guide/equipdetail/894?ppc" #网页地址resrequests.get(url0)contentres.contenthtmletree.HTML(content)namehtml.xpath(//*[id"row-move"]/div[2]/div/div[2…

TCP解读

TCP 三次握手 第一次: 客户端 - - > 服务端 发送目标&#xff1a;我要连你 第二次: 客户端 < - - 服务端 发送目标&#xff1a;可以 第三次: 客户端 - - > 服务端 发送目标&#xff1a;收到 TCP 详解&#xff1a;https://blog.csdn.net/sinat_36629696/article/detail…

Mysql 内置函数大全

转载并整理&#xff1a; 包括&#xff1a; 数值进制&#xff1b; 字符串长度、截取、填充、删除、拼接等&#xff1b; 文件读取&#xff1b; 数值绝对值、正负判断、取模、取整、次方、对数、开方、三角函数、反三角函数、随机数、弧度和角度、精确度保留、最大值和最小值…