2023年12月8日18:15:22

master
zhangmeng 2023-12-08 18:15:55 +08:00
parent dff5d100ee
commit f2f73411a0
3 changed files with 243 additions and 3 deletions

View File

@ -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<ChatFriend> listView;
@FXML
public TextArea content;
private ObservableList<ChatFriend> 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<ChatFriend> call(ListView<ChatFriend> listView) {
Label label = new Label();
label.setPrefWidth(200);
ListCell<ChatFriend> 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<String, Object> query = new HashMap<>();
query.put("id", "1");
String json = HttpUtils.get_request(HOST + "/chatFriend/list", query);
log.info(json);
List<ChatFriend> 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;
}
}

View File

@ -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<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
@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();
}
}
}

View File

@ -15,7 +15,7 @@
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0">
<items>
<ListView prefHeight="200.0" prefWidth="200.0"/>
<ListView fx:id="listView" prefHeight="200.0" prefWidth="200.0"/>
<AnchorPane minHeight="0.0" minWidth="0.0" opacity="1" prefHeight="160.0" prefWidth="100.0">
<children>
<VBox prefHeight="447.0" prefWidth="895.0" AnchorPane.bottomAnchor="200.0"
@ -23,7 +23,7 @@
<AnchorPane layoutY="447.0" prefHeight="200.0" prefWidth="895.0"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0">
<children>
<TextArea layoutX="14.0" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0"
<TextArea fx:id="content" layoutX="14.0" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0"
AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="25.0" style="-fx-border-width: 0;-fx-border-style: none;"/>
<HBox prefHeight="100.0" prefWidth="200.0" AnchorPane.bottomAnchor="173.0"