使用javaSwing搭建一个简单的聊天室
生活随笔
收集整理的這篇文章主要介紹了
使用javaSwing搭建一个简单的聊天室
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這個是因為幫朋友做作業記錄一下,現場學習嗄,都忘了。好了不多說了。
?1、首先得知道Swing,Swing是一個新型的java窗口工具(還是那么Love Orange W,哈哈哈)
2、聊天室怎么少得了Socket(套接字)
以上就是兩個窗口聊天的主要用到底工具(功能)
1、聊天室多人聊天的,所以我們會以客戶端和服務端兩端就夠了
2、我們開始寫服務端代碼,其實服務端和客戶端代碼都是一樣的,會一個就會兩個了,主要的就是在于區分Socket的端口與連接端口區別。不多bb了。上代碼
2.1、服務端的代碼
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.OutputStream; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter;/*** @Author: create_By:* @Data:Created in 2019/12/24 23:26* @Version:* @Acton: QQ服務系統*/ public class QQServerSystem {private JFrame frame; // 窗口private Container container; // 創中的容器對象public JTextArea txtList; // 文本列表框public JTextField txtMsg; // 文本發送框public JButton btn; // 發送按鈕public String addMsg = "未連接";public OutputStream os; //發送消息的public QQServerSystem() {frame = new JFrame("九哥的QQ服務端");frame.setBounds(400, 300, 800, 600); //設置窗口大小位置frame.setLayout(new BorderLayout()); //設置樣式container = frame.getContentPane(); //窗口生成容器txtList = new JTextArea(5, 20); //生成文本域的大小container.add(txtList, BorderLayout.CENTER); //把文本加入容器中,并設置布局JPanel txtPanel = new JPanel();txtPanel.setLayout(new FlowLayout(FlowLayout.LEADING));txtMsg = new JTextField(60); //設置消息文本行高btn = new JButton("發送");btn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {//實現給客戶端發送消息的功能//1、點擊發送獲取消息框中的信息String msgText = txtMsg.getText();//2、處理文本if (!"".equals(msgText) && msgText != null) { //判斷是有文字的才會做處理//1、顯示到自己的連天窗口txtList.append("我: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));txtList.append("\r\n");txtList.append(msgText);txtList.append("\r\n");txtMsg.setText("");//2、發送byte[] sendBuf = msgText.getBytes();try {if (os != null) {os.write(sendBuf);}} catch (IOException e1) {e1.printStackTrace();}}}});txtPanel.add(txtMsg); //消息框加入面板中txtPanel.add(btn); //按鈕加入面板中container.add(txtPanel, BorderLayout.SOUTH); //把面板加入容器中,并設置布局startServerThread();refreshMsgList();}/* 刷新消息列表 */private void refreshMsgList() {String txt = txtList.getText();txtList.setText(txt + addMsg + "\n");}/* 啟動線程 */private void startServerThread() {new ServerListenThread(this).start();}/* 啟動面板 */public void start() {frame.setVisible(true); //設置可以顯示} } import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter;/*** @Author: create_By:* @Data:Created in 2019/12/24 23:47* @Version:* @Acton: 繼承線程讓其成為線程類*/ public class ServerListenThread extends Thread {private ServerSocket serverSocket;private Socket socket;private InputStream is;public QQServerSystem qqs;public ServerListenThread(QQServerSystem qqs) {super();this.qqs = qqs;}@Overridepublic void run() {//實現監聽8888端口,接收客戶端發送的消息,并顯示到界面try {serverSocket = new ServerSocket(8888, 1000); //創建服務端套接字并設置端口socket = serverSocket.accept(); //創建套接字is = socket.getInputStream(); //獲取輸入流qqs.os = socket.getOutputStream(); //獲取輸出流while (true) {if (socket.isConnected()) {byte[] buff = new byte[1024]; //設置一個臨時緩沖區int len = is.read(buff); //從輸入流讀取字節長度byte[] eBuff = new byte[len]; //根據實際長度,定義一個輸入緩沖區System.arraycopy(buff, 0, eBuff, 0, len); //拷貝數據String text = new String(eBuff); //把字節轉換字符qqs.txtList.append("對方: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));qqs.txtList.append("\r\n");qqs.txtList.append(text);qqs.txtList.append("\r\n");}}} catch (IOException e) {e.printStackTrace();}} } public class ServerMain {public static void main(String[] args) {QQServerSystem qs = new QQServerSystem();qs.start();} }?2.2、客戶端的代碼
?
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.OutputStream; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter;/*** @Author: create_By:* @Data:Created in 2019/12/24 23:56* @Version:* @Acton: QQ客戶端系統*/ public class QQClientSystem{private JFrame frame; //窗口private Container container; //創中的容器對象public JTextArea txtList; //文本列表框public JTextField txtMsg; //文本發送框public JButton btn; //發送按鈕public String addMsg = "未連接";public OutputStream os; //用于發送信息。public QQClientSystem() {frame = new JFrame("九哥的QQ客戶端");frame.setBounds(400, 300, 800, 600); // 設置窗口大小和位置frame.setLayout(new BorderLayout());container = frame.getContentPane();txtList = new JTextArea(5, 20);container.add(txtList, BorderLayout.CENTER);JPanel txtPanel = new JPanel();txtPanel.setLayout(new FlowLayout(FlowLayout.LEADING));txtMsg = new JTextField(60);btn = new JButton("發送");btn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// 實現給服務器端發送消息的部分//1、點擊發送獲取消息框中的信息String msgText = txtMsg.getText();//2、處理文本if(!"".equals(msgText) && msgText != null){ //判斷是有文字的才會做處理//2、發送byte[] sendBuf = msgText.getBytes();try {if (os != null){os.write(sendBuf);}} catch (IOException e1) {e1.printStackTrace();}txtList.append("我: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));txtList.append("\r\n");txtList.append(msgText);txtList.append("\r\n");txtMsg.setText("");}}});txtPanel.add(txtMsg);txtPanel.add(btn);container.add(txtPanel, BorderLayout.SOUTH);startRequestThread();refreshMsgList();}public void startRequestThread() {new ClientRequestThread(this).start();}public void refreshMsgList() {String str = txtList.getText();txtList.setText(str + addMsg + "\n");}public void start(){frame.setVisible(true);}}?
import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter;/*** @Author: create_By:* @Data:Created in 2019/12/24 23:58* @Version:* @Acton:*/ public class ClientRequestThread extends Thread {private Socket socket;private InputStream is;QQClientSystem qqc;public ClientRequestThread(QQClientSystem qqc) {this.qqc = qqc;}@Overridepublic void run() {// 實現連接服務器的功能,并可以接收服務器端發送的消息,顯示到程序界面try {socket = new Socket("localhost", 8888);is = socket.getInputStream();qqc.os = socket.getOutputStream();} catch (IOException e1) {e1.printStackTrace();}while (true) {if (socket.isConnected()) { //已經連接才做以下處理byte[] buff = new byte[1024]; //設置一個臨時緩沖區int len = 0; //從輸入流讀取字節長度try {len = is.read(buff);} catch (IOException e) {e.printStackTrace();}byte[] eBuff = new byte[len]; //根據實際長度,定義一個輸入緩沖區System.arraycopy(buff, 0, eBuff, 0, len); //拷貝數據String text = new String(eBuff); //把字節轉換字符qqc.txtList.append("對方: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));qqc.txtList.append("\r\n");qqc.txtList.append(text);qqc.txtList.append("\r\n");}}}} public class ClientMain {public static void main(String[] args) {QQClientSystem qc = new QQClientSystem();qc.start();} }這個直接復制到自己的代碼中運行即可,然后后續的優化自己改下就行了。因為相對簡潔,我們只需要學習部分基礎功能和知識即可。如果本章對你有所幫助,請點個贊收藏一下,蟹蟹。
總結
以上是生活随笔為你收集整理的使用javaSwing搭建一个简单的聊天室的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PMS-产品管理系统(搭建开发环境)
- 下一篇: linux命令行启动向日葵无法编辑,li