這個是因爲幫朋友做作業記錄一下,現場學習嗄,都忘了。好了不多說了。
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() {
@Override
public 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;
}
@Override
public 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() {
@Override
public 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;
}
@Override
public 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();
}
}
這個直接複製到自己的代碼中運行即可,然後後續的優化自己改下就行了。因爲相對簡潔,我們只需要學習部分基礎功能和知識即可。如果本章對你有所幫助,請點個贊收藏一下,蟹蟹。