Vert.x实战四:TCP客户端之间以角色和同一角色连接顺序通过服务端转接通信

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.x的TCP服务端和客户端配置:https://blog.csdn.net/haoranhaoshi/article/details/89297022 

本篇:客户端针对特定角色、特定连接顺序给特定客户端发送消息。

package VertxTCPRoleIndexTest;

import com.alibaba.fastjson.JSON;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VertxTCPServer extends AbstractVerticle {
    /**
     * 客户端角色和Socket连接列表的映射集合
     */
    private Map<String, List<NetSocket>> roleMap = new HashMap<>();

    @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 sourceRole = jsonObject.getString("sourceRole");
                if (sourceRole != null) {
                    List<NetSocket> netSocketList = roleMap.get(sourceRole);
                    if (netSocketList == null) {
                        netSocketList = new ArrayList<>();
                    }

                    netSocketList.add(socket);
                    roleMap.put(sourceRole, netSocketList);
                    return;
                }

                String targetRole = jsonObject.getString("targetRole");
                int targetIndex = jsonObject.getInteger("targetIndex");
                String content = jsonObject.getString("content");
                roleMap.get(targetRole).get(targetIndex).write(content);
            });

            // 监听客户端的退出连接
            socket.closeHandler(close -> {
                for(Map.Entry mapEntry : roleMap.entrySet()){
                    List<NetSocket> netSocketList = (List<NetSocket>)mapEntry.getValue();
                    String sourceRole = (String)mapEntry.getKey();
                    for(NetSocket netSocket : netSocketList){
                        if(netSocket == socket){
                            netSocketList.remove(netSocket);
                            System.out.println("客户端(角色为" + sourceRole + ")退出连接");
                            // 删除后角色对应的Socket连接列表无子项,则删除此角色与对应Socket连接列表的映射
                            if(netSocketList.size() == 0){
                                roleMap.remove(mapEntry.getKey());
                            }

                            System.out.println("客户端角色和Socket连接列表的映射集合已更新");
                        }
                    }
                }
            });
        });

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

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

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.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class VertxTCPClient extends AbstractVerticle {
    /**
     * 客户端角色
     */
    private static String SOURCEROLE = "C";
    /**
     * 客户端Socket连接
     */
    private static NetSocket netSocket;

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

        // 连接服务器
        client.connect(33323, "localhost", conn -> {
            if (conn.succeeded()) {
                System.out.println("客户端(角色为" + SOURCEROLE + ")连接服务端成功,时间:" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                netSocket = conn.result();
                // 向服务端发送客户端角色
                JSONObject roleJsonObject = new JSONObject();
                roleJsonObject.put("sourceRole", SOURCEROLE);
                netSocket.write(Buffer.buffer(roleJsonObject.toJSONString()));

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

    }

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

 

上一篇:@寒冬winter 大神的css作业问题


下一篇:Android手游外挂入侵----寓攻于守,方能破敌