Java實(shí)現(xiàn)簡(jiǎn)單局域網(wǎng)聊天室
本文實(shí)例為大家分享了Java實(shí)現(xiàn)簡(jiǎn)單局域網(wǎng)聊天室的具體代碼,供大家參考,具體內(nèi)容如下
Java 的Socket編程:
1、TCP協(xié)議是面向連接的、可靠的、有序的、以字節(jié)流的方式發(fā)送數(shù)據(jù),通過三次握手方式建立連接,形成傳輸數(shù)據(jù)的通道,在連接中進(jìn)行大量數(shù)據(jù)的傳輸,效率會(huì)稍低
2、Java中基于TCP協(xié)議實(shí)現(xiàn)網(wǎng)絡(luò)通信的類
- 客戶端的Socket類
- 服務(wù)器端的ServerSocket類

3、Socket通信的步驟
① 創(chuàng)建ServerSocket和Socket
② 打開連接到Socket的輸入/輸出流
③ 按照協(xié)議對(duì)Socket進(jìn)行讀/寫操作
④ 關(guān)閉輸入輸出流、關(guān)閉Socket
4、服務(wù)器端:
① 創(chuàng)建ServerSocket對(duì)象,綁定監(jiān)聽端口
② 通過accept()方法監(jiān)聽客戶端請(qǐng)求
③ 連接建立后,通過輸入流讀取客戶端發(fā)送的請(qǐng)求信息
④ 通過輸出流向客戶端發(fā)送鄉(xiāng)音信息
⑤ 關(guān)閉相關(guān)資源
5、客戶端:
① 創(chuàng)建Socket對(duì)象,指明需要連接的服務(wù)器的地址和端口號(hào)
② 連接建立后,通過輸出流想服務(wù)器端發(fā)送請(qǐng)求信息
③ 通過輸入流獲取服務(wù)器響應(yīng)的信息
④ 關(guān)閉響應(yīng)資源
實(shí)現(xiàn)的聊天室例子:
實(shí)現(xiàn)的效果是如下:

服務(wù)端代碼:
package socket.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
/**
* @author 超
* Create by fengc on 2018/7/25 21:21
*/
public class Server extends Thread{
ServerUI ui;
ServerSocket ss;
BufferedReader reader;
PrintWriter writer;
public Server(ServerUI ui) {
this.ui = ui;
this.start();
}
@Override
public void run() {
try {
ss = new ServerSocket(8081);
ui.clients=new ArrayList<>();
println("啟動(dòng)服務(wù)器成功:端口8081");
while (true) {
println("等待客戶端鏈接.......................................");
Socket client = ss.accept();
ui.clients.add(client);
println("連接成功,客戶端請(qǐng)求服務(wù)端的詳細(xì)信息:" + client.toString());
new ListenerClient(ui, client);
}
} catch (IOException e) {
println("啟動(dòng)服務(wù)器失?。憾丝?081");
println(e.toString());
e.printStackTrace();
}
}
public synchronized void sendMsg(String msg) {
try {
for (int i = 0; i < ui.clients.size(); i++) {
Socket client = ui.clients.get(i);
writer = new PrintWriter(client.getOutputStream(), true);
writer.println(msg);
}
} catch (Exception e) {
println(e.toString());
}
}
public void println(String s) {
if (s != null) {
s = "服務(wù)端打印消息:" + s;
this.ui.taShow.setText(this.ui.taShow.getText() + s + "\n");
System.out.println(s + "\n");
}
}
public void closeServer() {
try {
if (ss != null)
ss.close();
if (reader != null)
reader.close();
if (writer != null)
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package socket.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* @author 超
* Create by fengc on 2018/7/25 21:33
* 這個(gè)類是服務(wù)器端的等待客戶端發(fā)送信息*
*/
public class ListenerClient extends Thread{
BufferedReader reader;
PrintWriter writer;
ServerUI ui;
Socket client;
public ListenerClient(ServerUI ui, Socket client) {
this.ui = ui;
this.client=client;
this.start();
}
//為每一個(gè)客戶端創(chuàng)建線程等待接收信息,然后把信息廣播出去
@Override
public void run() {
String msg = "";
while (true) {
try {
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream(), true);
msg = reader.readLine();
sendMsg(msg);
} catch (IOException e) {
println(e.toString());
break;
}
if (msg != null && msg.trim() != "") {
println("客戶端 " + msg);
}
}
}
//把信息廣播到所有用戶
public synchronized void sendMsg(String msg) {
try {
for (int i = 0; i < ui.clients.size(); i++) {
Socket client = ui.clients.get(i);
writer = new PrintWriter(client.getOutputStream(), true);
writer.println(msg);
}
} catch (Exception e) {
println(e.toString());
}
}
public void println(String s) {
if (s != null) {
this.ui.taShow.setText(this.ui.taShow.getText() + s + "\n");
System.out.println(s + "\n");
}
}
}
package socket.server;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.Socket;
import java.util.List;
/**
* @author 超
* Create by fengc on 2018/7/25 21:21
*/
public class ServerUI extends JFrame {
public static void main(String[] args) {
new ServerUI();
}
public JButton btStart;//啟動(dòng)服務(wù)器
public JButton btSend;//發(fā)送信息按鈕
public JTextField tfSend;//需要發(fā)送的文本信息
public JTextArea taShow;//信息展示
public Server server;//用來監(jiān)聽客戶端連接
static List<Socket> clients;//保存連接到服務(wù)器的客戶端
public ServerUI() {
super("服務(wù)器端");
btStart = new JButton("啟動(dòng)服務(wù)");
btSend = new JButton("發(fā)送信息");
tfSend = new JTextField(10); //裝在輸入文字
taShow = new JTextArea();
//點(diǎn)擊按鈕,所做的是事情,啟動(dòng)服務(wù)器
btStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
server = new Server(ServerUI.this);
}
});
//點(diǎn)擊發(fā)送消息按鈕
btSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
server.sendMsg(tfSend.getText());
tfSend.setText("");
}
});
//初始化界面
this.addWindowListener(new WindowAdapter() {
//關(guān)閉按鈕點(diǎn)擊事件
public void windowClosing(WindowEvent e) {
int a = JOptionPane.showConfirmDialog(null, "確定關(guān)閉嗎?", "溫馨提示",
JOptionPane.YES_NO_OPTION);
if (a == 1) {
server.closeServer();
System.exit(0); // 關(guān)閉
}
}
});
//底部啟動(dòng)服務(wù)按鈕與發(fā)送消息按鈕
JPanel top = new JPanel(new FlowLayout());
top.add(tfSend);
top.add(btSend);
top.add(btStart);
this.add(top, BorderLayout.SOUTH);
//中部顯示消息欄 信息展示
final JScrollPane sp = new JScrollPane();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setViewportView(this.taShow);
this.taShow.setEditable(false);
this.add(sp, BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
this.setLocation(100, 200);
this.setVisible(true);
}
}
客戶端代碼:
package socket.clinet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* @author 超
* Create by fengc on 2018/7/25 21:41
*/
public class Client extends Thread {
ClientUI ui;
Socket client;
BufferedReader reader;
PrintWriter writer;
public Client(ClientUI ui) {
this.ui = ui;
try {
String ip = ui.tfIP.getText(); //得到輸入的ip地址
int port = Integer.parseInt(ui.tfPort.getText()); //得到輸入的端口
client = new Socket(ip, port);//這里設(shè)置連接服務(wù)器端的IP的端口
println("連接服務(wù)器成功,服務(wù)器端口地址:" + port);
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new PrintWriter(client.getOutputStream(), true);
String name = ui.tfName.getText();
if (name == null || "".equals(name)) {
name = "匿名者";
}
sendMsg("會(huì)員 " + name + ",登錄上來了........................");
// 如果為 true,則 println、printf 或 format 方法將刷新輸出緩沖區(qū)
} catch (NumberFormatException nu) {
println("端口請(qǐng)輸入正確.......");
nu.printStackTrace();
} catch (IOException e) {
println("連接服務(wù)器失敗:請(qǐng)輸入正確的IP地址與端口");
println(e.toString());
e.printStackTrace();
}
this.start();
}
public void run() {
String msg = "";
while (true) {
try {
msg = reader.readLine();
} catch (IOException e) {
println("服務(wù)器斷開連接");
break;
}
if (msg != null && msg.trim() != "") {
println(msg);
}
}
}
public void sendMsg(String msg) {
try {
writer.println(msg);
} catch (Exception e) {
println(e.toString());
}
}
public void println(String s) {
if (s != null) {
this.ui.taShow.setText(this.ui.taShow.getText() + s + "\n");
System.out.println(s + "\n");
}
}
}
package socket.clinet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* @author 超
* Create by fengc on 2018/7/25 21:40
*/
public class ClientUI extends JFrame {
public static void main(String[] args) {
new ClientUI();
}
public JButton btStart;
public JButton btSend;
public JTextField tfSend; //裝在輸入文字
public JTextPane nameText; //輸入名字
public JTextPane ipTex; //輸入名字
public JTextPane portText; //輸入名字
public JTextField tfName; //服務(wù)器ip
public JTextField tfIP; //服務(wù)器ip
public JTextField tfPort; //服務(wù)器端口
public JTextArea taShow;
public Client server;
public ClientUI() {
super("客戶端");
btStart = new JButton("啟動(dòng)連接");
btSend = new JButton("發(fā)送信息");
tfSend = new JTextField(20);
tfIP = new JTextField(8);
tfPort = new JTextField(3);
tfName = new JTextField(6);
nameText = new JTextPane();nameText.setText("登錄名");nameText.setEditable(false);
ipTex = new JTextPane();ipTex.setText("服務(wù)地址");ipTex.setEditable(false);
portText = new JTextPane();portText.setText("服務(wù)端口");portText.setEditable(false);
taShow = new JTextArea();
//啟動(dòng)鏈接按鈕事件
btStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
server = new Client(ClientUI.this);
}
});
//發(fā)送按鈕事件
btSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = tfName.getText();
if (name == null || "".equals(name)) {
name = "匿名者";
}
server.sendMsg(name + ":" + tfSend.getText());
tfSend.setText("");
}
});
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int a = JOptionPane.showConfirmDialog(null, "確定關(guān)閉嗎?", "溫馨提示",
JOptionPane.YES_NO_OPTION);
if (a == 1) {
System.exit(0); // 關(guān)閉
}
}
});
//底部的發(fā)送信息框與鏈接按鈕
JPanel top = new JPanel(new FlowLayout());
top.add(tfSend); //發(fā)送文本
top.add(btSend); //發(fā)送按鈕
this.add(top, BorderLayout.SOUTH); //加載到底部
//頭部放連接服務(wù)的
JPanel northJpannel = new JPanel(new FlowLayout());
northJpannel.add(nameText);
northJpannel.add(tfName);
northJpannel.add(ipTex);
northJpannel.add(tfIP);
northJpannel.add(portText);
northJpannel.add(tfPort);
northJpannel.add(btStart);
this.add(northJpannel,BorderLayout.NORTH); //加載到頭部
final JScrollPane sp = new JScrollPane();
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setViewportView(this.taShow);
this.taShow.setEditable(false);
this.add(sp, BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 400);
this.setLocation(600, 200);
this.setVisible(true);
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java實(shí)現(xiàn)局域網(wǎng)聊天室功能(私聊、群聊)
- Java實(shí)現(xiàn)局域網(wǎng)聊天小程序
- Java用局域網(wǎng)實(shí)現(xiàn)聊天室功能
- java?socket實(shí)現(xiàn)局域網(wǎng)聊天
- Java創(chuàng)建多線程局域網(wǎng)聊天室實(shí)例
- Java多線程局域網(wǎng)聊天室的實(shí)現(xiàn)
- java局域網(wǎng)聊天小程序
- java實(shí)現(xiàn)簡(jiǎn)易局域網(wǎng)聊天功能
- 基于java編寫局域網(wǎng)多人聊天室
- java+socket實(shí)現(xiàn)簡(jiǎn)易局域網(wǎng)聊天室
相關(guān)文章
SpringBoot 如何自定義請(qǐng)求參數(shù)校驗(yàn)
這篇文章主要介紹了SpringBoot 如何自定義請(qǐng)求參數(shù)校驗(yàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
java實(shí)現(xiàn)識(shí)別二維碼圖片功能
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)識(shí)別二維碼圖片功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
RocketMQ4.5.X 實(shí)現(xiàn)修改生產(chǎn)者消費(fèi)者日志保存路徑
這篇文章主要介紹了RocketMQ4.5.X 實(shí)現(xiàn)修改生產(chǎn)者消費(fèi)者日志保存路徑方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
SpringBoot瘦身打包部署的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot瘦身打包部署的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
Java注冊(cè)郵箱激活驗(yàn)證實(shí)現(xiàn)代碼
這篇文章主要介紹了Java注冊(cè)郵箱激活驗(yàn)證實(shí)現(xiàn)代碼,有需要的朋友可以參考一下2013-12-12
IDEA 2021.2 激活教程及啟動(dòng)報(bào)錯(cuò)問題解決方法
這篇文章主要介紹了IDEA 2021.2 啟動(dòng)報(bào)錯(cuò)及激活教程,文章開頭給大家介紹了idea2021最新激活方法,關(guān)于idea2021啟動(dòng)報(bào)錯(cuò)的問題小編也給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-10-10
詳解SpringBoot中實(shí)現(xiàn)依賴注入功能
這篇文章主要介紹了詳解SpringBoot中實(shí)現(xiàn)依賴注入功能,SpringBoot的實(shí)現(xiàn)方式基本都是通過注解實(shí)現(xiàn)的。有興趣的可以了解一下。2017-04-04

