客户端部分搭建思路及实现
在阅读本篇之前,建议先了解Socket的基础相关知识,本文接上篇《Socket基础知识》:https://blog.csdn.net/Jiang216/article/details/108070585
1.1 构建客户端可视化界面
搭建ClientView类,该类继承JFrame类,并实现ActionListener, KeyListener两个事件监听接口。添加图形操作控件如下:
private JTextArea chatArea;//聊天内容区
private JTextField inputMessage;//聊天输入框
private JTextField inputName;//用户名输入框
private JButton btnSend;//发送按钮
private JLabel labelNick;
private JPanel jp1,jp2;
private JScrollPane scrollPane;
private JLabel labelHost;
private JLabel labelPort;
private JTextField hostAddress;//服务器地址输入框
private JTextField hostPort;//服务器端口输入框
private JButton btnConnect;//连接/断开服务器按钮
private void initView(){
chatArea=new JTextArea(20,20);
chatArea.setEditable(false);
scrollPane=new JScrollPane(chatArea);
inputMessage=new JTextField(15);
btnSend=new JButton("发送");
jp1=new JPanel();
labelHost=new JLabel("主机地址");
hostAddress=new JTextField(15);
hostAddress.setText("localhost");
labelPort=new JLabel("端口号");
hostPort=new JTextField(4);
hostPort.setText("8765");
btnConnect=new JButton("连接");
jp1.add(labelHost);
jp1.add(hostAddress);
jp1.add(labelPort);
jp1.add(hostPort);
jp1.add(btnConnect);
labelNick=new JLabel("昵称:");
inputName=new JTextField(8);
jp2=new JPanel();
jp2.add(labelNick);
jp2.add(inputName);
inputName.setText("用户0");
jp1.setLayout(new FlowLayout(FlowLayout.CENTER));
jp2.add(inputMessage);
jp2.add(btnSend);
jp2.setLayout(new FlowLayout(FlowLayout.CENTER));
add(jp1,BorderLayout.NORTH);
add(scrollPane,BorderLayout.CENTER);
add(jp2,BorderLayout.SOUTH);
setTitle("聊天室");
setSize(500,500);
setLocation(450,150);