Vert.x实战五:TCP客户端之间以ID通过服务端转接通信

news/2024/5/17 16:46:12 标签: 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

package VertxTCPIdTest;

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 {
    private Map<String, NetSocket> idMap = 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 id = jsonObject.getString("id");
                if (id != null) {
                    if(idMap.get(id) != null){
                        socket.write("id已经存在,当前客户端id有:" + idMap.keySet().toString());
                    }else{
                        idMap.put(id, socket);
                        System.out.println("客户端" + id + "已加入,当前客户端id有:" + idMap.keySet().toString());
                    }
                } else{
                    String messageHead = jsonObject.getString("messageHead");
                    String messageBody = jsonObject.getString("messageBody");
                    if(messageHead != null){
                        NetSocket netSocket = idMap.get(messageHead);
                        if(netSocket == null){
                            socket.write("客户端" + messageHead +"未连接或者已经退出连接");
                        }else{
                            netSocket.write(messageBody);
                        }
                    }
                }
            });

            // 监听客户端的退出连接
            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 VertxTCPIdTest;

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 = "3";
    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();
            // messageHead为另一个客户端的ID,messageBody为给另一个客户端的内容
            messageJsonObject.put("messageHead", message.split(":")[0]);
            messageJsonObject.put("messageBody", message.split(":")[1]);
            netSocket.write(Buffer.buffer(messageJsonObject.toJSONString()));
        }
    }
}

 


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

相关文章

thinkPHP验证码报错: Call to undefined function captcha_src()

问题出现的原因可能有&#xff1a; 1. captcha扩展缺失&#xff1b; 2. captcha扩展与当前thinkPHP版本不兼容。 thinkPHP6.0以下版本只能使用 captcha2.0以下版本&#xff0c;不支持2.0版本。 利用composer依赖下载 composer require topthink/think-captcha 后面添版本号 在p…

【BFS】【迭代】【Java】Leetcode 515. 在每个树行中找最大值

您需要在二叉树的每一行中找到最大的值。 示例&#xff1a; 输入: 1/ \3 2/ \ \ 5 3 9 输出: [1, 3, 9] import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue;public class EveryRowMax {public static void…

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…

【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…