From f2f73411a0ae1e6a67eafeaa184e65995e53abc3 Mon Sep 17 00:00:00 2001 From: zhangmeng <1334717033@qq.com> Date: Fri, 8 Dec 2023 18:15:55 +0800 Subject: [PATCH] =?UTF-8?q?2023=E5=B9=B412=E6=9C=888=E6=97=A518:15:22?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/ChatAppImplController.java | 190 +++++++++++++++++- .../tools/nettyClient/NettyClient.java | 52 +++++ src/main/resources/fxml/chat-app-impl.fxml | 4 +- 3 files changed, 243 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/zhangmeng/tools/nettyClient/NettyClient.java diff --git a/src/main/java/com/zhangmeng/tools/controller/ChatAppImplController.java b/src/main/java/com/zhangmeng/tools/controller/ChatAppImplController.java index 9298bcf..24f839d 100644 --- a/src/main/java/com/zhangmeng/tools/controller/ChatAppImplController.java +++ b/src/main/java/com/zhangmeng/tools/controller/ChatAppImplController.java @@ -1,19 +1,81 @@ package com.zhangmeng.tools.controller; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.zhangmeng.tools.nettyClient.NettyClient; +import com.zhangmeng.tools.utils.AlertUtils; +import com.zhangmeng.tools.utils.HttpUtils; import com.zhangmeng.tools.utils.ImagePath; +import com.zhangmeng.tools.utils.ResourcesUtils; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; import javafx.fxml.FXML; -import javafx.scene.control.Button; +import javafx.geometry.Pos; +import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; +import javafx.scene.input.KeyCode; +import javafx.scene.layout.HBox; +import javafx.scene.paint.Paint; +import javafx.scene.text.Font; +import javafx.util.Callback; +import lombok.Data; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.drafts.Draft_6455; +import org.java_websocket.handshake.ServerHandshake; + +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Slf4j public class ChatAppImplController { + public enum Type{ + ws("ws"), + wss("wss") + ; + + Type(String name) { + this.name = name; + } + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + + public static String HOST = "http://localhost:8083"; + + public static int netty_port = 8888; + public static String netty_host = "localhost"; @FXML public Button file_button; + @FXML + public ListView listView; + + @FXML + public TextArea content; + + private ObservableList chatFriendList = FXCollections.observableArrayList(); + + public static final String color_cell = "#f4f4f4"; + + private WebSocketClient webSocketClient; + private NettyClient nettyClient; + @FXML public void initialize() { @@ -22,6 +84,132 @@ public class ChatAppImplController { iv.setPreserveRatio(true); iv.setFitWidth(18); file_button.setGraphic(iv); + init_list_view(); + listView.setItems(chatFriendList); + content.setOnKeyPressed(event -> { + if (event.getCode() == KeyCode.ENTER) { + sendMsg(); + content.clear(); + } + + }); + file_button.setOnAction(event -> getChatFriendList()); + init_netty_client(); + } + + public void init_netty_client(){ + if (webSocketClient == null) { + webSocketClient(ChatAppImplController.Type.ws, netty_host, netty_port, "/websocket", "userId=1&source=pc"); + } + } + + public void sendMsg(){ + if (content.getText().isEmpty()){ + AlertUtils.alert_warning("请输入文本在发送!"); + return; + } + //webSocketClient.send(content.getText()); + nettyClient.sendMsg(content.getText()); + } + + public void webSocketClient(ChatAppImplController.Type type, String socket_address, int socket_port, String path , String params) { + try { + webSocketClient = new WebSocketClient(new URI(type.name + "://" + socket_address + ":" + socket_port + path + "?" + params), new Draft_6455()) { + //连接服务端时触发 + @Override + public void onOpen(ServerHandshake handshakedata) { + log.info("websocket客户端和服务器连接成功"); + } + //收到服务端消息时触发 + @Override + public void onMessage(String message) { + log.info("websocket客户端收到消息={}", message); + } + //和服务端断开连接时触发 + @Override + public void onClose(int code, String reason, boolean remote) { + log.info("websocket客户端退出连接"); + } + //连接异常时触发 + @Override + public void onError(Exception ex) { + log.info("websocket客户端和服务器连接发生错误={}", ex.getMessage()); + } + }; + webSocketClient.connect(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void init_list_view(){ + listView.setCellFactory(new Callback<>() { + private int position; + @Override + public ListCell call(ListView listView) { + Label label = new Label(); + label.setPrefWidth(200); + ListCell listCell = new ListCell<>() { + @Override + protected void updateItem(ChatFriend chatFriend, boolean b) { + super.updateItem(chatFriend, b); + if (!b) { + HBox hBox = new HBox(25); + hBox.setAlignment(Pos.CENTER); + label.setText(chatFriend.getFriend_name()); + label.setTextFill(Paint.valueOf("#000000")); + label.setFont(Font.font(20)); + hBox.getChildren().add(label); + this.setGraphic(hBox); + } + this.setStyle("-fx-background-color: " + color_cell); + } + }; + + listCell.hoverProperty().addListener((observableValue, aBoolean, t1) -> { + if (t1 && !label.getText().equals("")) { + position = listView.getItems().indexOf(label.getText()); + label.setFont(new Font(16)); + listView.getFocusModel().focus(position); + listCell.setStyle("-fx-background-color: #369e7d"); + } else { + label.setPrefHeight(20); + label.setFont(new Font(13)); + listCell.setStyle("-fx-background-color: " + color_cell); + } + }); + + return listCell; + } + }); + } + + public void getChatFriendList() { + Map query = new HashMap<>(); + query.put("id", "1"); + String json = HttpUtils.get_request(HOST + "/chatFriend/list", query); + log.info(json); + + List list = JSON.parseArray(json, ChatFriend.class); + if (!list.isEmpty()) { + chatFriendList.setAll(list); + } + } + + @Data + public static class ChatFriend { + + public ChatFriend(String friend_id, String friend_name, String self_id, String self_name) { + this.friend_id = friend_id; + this.friend_name = friend_name; + this.self_id = self_id; + this.self_name = self_name; + } + + private String friend_id; + private String friend_name; + private String self_id; + private String self_name; } } diff --git a/src/main/java/com/zhangmeng/tools/nettyClient/NettyClient.java b/src/main/java/com/zhangmeng/tools/nettyClient/NettyClient.java new file mode 100644 index 0000000..43ca020 --- /dev/null +++ b/src/main/java/com/zhangmeng/tools/nettyClient/NettyClient.java @@ -0,0 +1,52 @@ +package com.zhangmeng.tools.nettyClient; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.string.StringDecoder; +import io.netty.handler.codec.string.StringEncoder; + +public class NettyClient { + private final String host; + private final int port; + + private ChannelFuture future; + + public NettyClient(String host, int port) { + this.host = host; + this.port = port; + } + + public void sendMsg(String text) { + future.channel().writeAndFlush(text); + } + + public void start(){ + EventLoopGroup group = new NioEventLoopGroup(); + + Bootstrap bootstrap = new Bootstrap(); + bootstrap.group(group) + .channel(NioSocketChannel.class) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) { + ch.pipeline().addLast(new StringDecoder()); + ch.pipeline().addLast(new StringEncoder()); + ch.pipeline().addLast(new SimpleChannelInboundHandler() { + @Override + protected void channelRead0(ChannelHandlerContext ctx, String msg) { + System.out.println("Received from server: " + msg); + } + }); + } + }); + try { + future = bootstrap.connect(host, port).sync(); + future.channel().closeFuture().sync(); + } catch (InterruptedException e) { + group.shutdownGracefully(); + } + } +} diff --git a/src/main/resources/fxml/chat-app-impl.fxml b/src/main/resources/fxml/chat-app-impl.fxml index d139031..67b28a9 100644 --- a/src/main/resources/fxml/chat-app-impl.fxml +++ b/src/main/resources/fxml/chat-app-impl.fxml @@ -15,7 +15,7 @@ AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"> - + -