使用javaSwing搭建一个简单的聊天室
生活随笔
收集整理的這篇文章主要介紹了
使用javaSwing搭建一个简单的聊天室
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
這個(gè)是因?yàn)閹团笥炎鲎鳂I(yè)記錄一下,現(xiàn)場(chǎng)學(xué)習(xí)嗄,都忘了。好了不多說(shuō)了。
?1、首先得知道Swing,Swing是一個(gè)新型的java窗口工具(還是那么Love Orange W,哈哈哈)
2、聊天室怎么少得了Socket(套接字)
以上就是兩個(gè)窗口聊天的主要用到底工具(功能)
1、聊天室多人聊天的,所以我們會(huì)以客戶(hù)端和服務(wù)端兩端就夠了
2、我們開(kāi)始寫(xiě)服務(wù)端代碼,其實(shí)服務(wù)端和客戶(hù)端代碼都是一樣的,會(huì)一個(gè)就會(huì)兩個(gè)了,主要的就是在于區(qū)分Socket的端口與連接端口區(qū)別。不多bb了。上代碼
2.1、服務(wù)端的代碼
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服務(wù)系統(tǒng)*/ public class QQServerSystem {private JFrame frame; // 窗口private Container container; // 創(chuàng)中的容器對(duì)象public JTextArea txtList; // 文本列表框public JTextField txtMsg; // 文本發(fā)送框public JButton btn; // 發(fā)送按鈕public String addMsg = "未連接";public OutputStream os; //發(fā)送消息的public QQServerSystem() {frame = new JFrame("九哥的QQ服務(wù)端");frame.setBounds(400, 300, 800, 600); //設(shè)置窗口大小位置frame.setLayout(new BorderLayout()); //設(shè)置樣式container = frame.getContentPane(); //窗口生成容器txtList = new JTextArea(5, 20); //生成文本域的大小container.add(txtList, BorderLayout.CENTER); //把文本加入容器中,并設(shè)置布局JPanel txtPanel = new JPanel();txtPanel.setLayout(new FlowLayout(FlowLayout.LEADING));txtMsg = new JTextField(60); //設(shè)置消息文本行高btn = new JButton("發(fā)送");btn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {//實(shí)現(xiàn)給客戶(hù)端發(fā)送消息的功能//1、點(diǎn)擊發(fā)送獲取消息框中的信息String msgText = txtMsg.getText();//2、處理文本if (!"".equals(msgText) && msgText != null) { //判斷是有文字的才會(huì)做處理//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、發(fā)送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); //把面板加入容器中,并設(shè)置布局startServerThread();refreshMsgList();}/* 刷新消息列表 */private void refreshMsgList() {String txt = txtList.getText();txtList.setText(txt + addMsg + "\n");}/* 啟動(dòng)線程 */private void startServerThread() {new ServerListenThread(this).start();}/* 啟動(dòng)面板 */public void start() {frame.setVisible(true); //設(shè)置可以顯示} } 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: 繼承線程讓其成為線程類(lèi)*/ 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() {//實(shí)現(xiàn)監(jiān)聽(tīng)8888端口,接收客戶(hù)端發(fā)送的消息,并顯示到界面try {serverSocket = new ServerSocket(8888, 1000); //創(chuàng)建服務(wù)端套接字并設(shè)置端口socket = serverSocket.accept(); //創(chuàng)建套接字is = socket.getInputStream(); //獲取輸入流qqs.os = socket.getOutputStream(); //獲取輸出流while (true) {if (socket.isConnected()) {byte[] buff = new byte[1024]; //設(shè)置一個(gè)臨時(shí)緩沖區(qū)int len = is.read(buff); //從輸入流讀取字節(jié)長(zhǎng)度byte[] eBuff = new byte[len]; //根據(jù)實(shí)際長(zhǎng)度,定義一個(gè)輸入緩沖區(qū)System.arraycopy(buff, 0, eBuff, 0, len); //拷貝數(shù)據(jù)String text = new String(eBuff); //把字節(jié)轉(zhuǎn)換字符qqs.txtList.append("對(duì)方: " + 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、客戶(hù)端的代碼
?
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客戶(hù)端系統(tǒng)*/ public class QQClientSystem{private JFrame frame; //窗口private Container container; //創(chuàng)中的容器對(duì)象public JTextArea txtList; //文本列表框public JTextField txtMsg; //文本發(fā)送框public JButton btn; //發(fā)送按鈕public String addMsg = "未連接";public OutputStream os; //用于發(fā)送信息。public QQClientSystem() {frame = new JFrame("九哥的QQ客戶(hù)端");frame.setBounds(400, 300, 800, 600); // 設(shè)置窗口大小和位置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("發(fā)送");btn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// 實(shí)現(xiàn)給服務(wù)器端發(fā)送消息的部分//1、點(diǎn)擊發(fā)送獲取消息框中的信息String msgText = txtMsg.getText();//2、處理文本if(!"".equals(msgText) && msgText != null){ //判斷是有文字的才會(huì)做處理//2、發(fā)送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() {// 實(shí)現(xiàn)連接服務(wù)器的功能,并可以接收服務(wù)器端發(fā)送的消息,顯示到程序界面try {socket = new Socket("localhost", 8888);is = socket.getInputStream();qqc.os = socket.getOutputStream();} catch (IOException e1) {e1.printStackTrace();}while (true) {if (socket.isConnected()) { //已經(jīng)連接才做以下處理byte[] buff = new byte[1024]; //設(shè)置一個(gè)臨時(shí)緩沖區(qū)int len = 0; //從輸入流讀取字節(jié)長(zhǎng)度try {len = is.read(buff);} catch (IOException e) {e.printStackTrace();}byte[] eBuff = new byte[len]; //根據(jù)實(shí)際長(zhǎng)度,定義一個(gè)輸入緩沖區(qū)System.arraycopy(buff, 0, eBuff, 0, len); //拷貝數(shù)據(jù)String text = new String(eBuff); //把字節(jié)轉(zhuǎn)換字符qqc.txtList.append("對(duì)方: " + 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();} }這個(gè)直接復(fù)制到自己的代碼中運(yùn)行即可,然后后續(xù)的優(yōu)化自己改下就行了。因?yàn)橄鄬?duì)簡(jiǎn)潔,我們只需要學(xué)習(xí)部分基礎(chǔ)功能和知識(shí)即可。如果本章對(duì)你有所幫助,請(qǐng)點(diǎn)個(gè)贊收藏一下,蟹蟹。
總結(jié)
以上是生活随笔為你收集整理的使用javaSwing搭建一个简单的聊天室的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: PMS-产品管理系统(搭建开发环境)
- 下一篇: java+rabbitMQ实现一对一聊天