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

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

服務端代碼:
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("啟動服務器成功:端口8081");
while (true) {
println("等待客戶端鏈接.......................................");
Socket client = ss.accept();
ui.clients.add(client);
println("連接成功,客戶端請求服務端的詳細信息:" + client.toString());
new ListenerClient(ui, client);
}
} catch (IOException e) {
println("啟動服務器失?。憾丝?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 = "服務端打印消息:" + 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
* 這個類是服務器端的等待客戶端發(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();
}
//為每一個客戶端創(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;//啟動服務器
public JButton btSend;//發(fā)送信息按鈕
public JTextField tfSend;//需要發(fā)送的文本信息
public JTextArea taShow;//信息展示
public Server server;//用來監(jiān)聽客戶端連接
static List<Socket> clients;//保存連接到服務器的客戶端
public ServerUI() {
super("服務器端");
btStart = new JButton("啟動服務");
btSend = new JButton("發(fā)送信息");
tfSend = new JTextField(10); //裝在輸入文字
taShow = new JTextArea();
//點擊按鈕,所做的是事情,啟動服務器
btStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
server = new Server(ServerUI.this);
}
});
//點擊發(fā)送消息按鈕
btSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
server.sendMsg(tfSend.getText());
tfSend.setText("");
}
});
//初始化界面
this.addWindowListener(new WindowAdapter() {
//關閉按鈕點擊事件
public void windowClosing(WindowEvent e) {
int a = JOptionPane.showConfirmDialog(null, "確定關閉嗎?", "溫馨提示",
JOptionPane.YES_NO_OPTION);
if (a == 1) {
server.closeServer();
System.exit(0); // 關閉
}
}
});
//底部啟動服務按鈕與發(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);//這里設置連接服務器端的IP的端口
println("連接服務器成功,服務器端口地址:" + 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("會員 " + name + ",登錄上來了........................");
// 如果為 true,則 println、printf 或 format 方法將刷新輸出緩沖區(qū)
} catch (NumberFormatException nu) {
println("端口請輸入正確.......");
nu.printStackTrace();
} catch (IOException e) {
println("連接服務器失?。赫堓斎胝_的IP地址與端口");
println(e.toString());
e.printStackTrace();
}
this.start();
}
public void run() {
String msg = "";
while (true) {
try {
msg = reader.readLine();
} catch (IOException e) {
println("服務器斷開連接");
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; //服務器ip
public JTextField tfIP; //服務器ip
public JTextField tfPort; //服務器端口
public JTextArea taShow;
public Client server;
public ClientUI() {
super("客戶端");
btStart = new JButton("啟動連接");
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("服務地址");ipTex.setEditable(false);
portText = new JTextPane();portText.setText("服務端口");portText.setEditable(false);
taShow = new JTextArea();
//啟動鏈接按鈕事件
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, "確定關閉嗎?", "溫馨提示",
JOptionPane.YES_NO_OPTION);
if (a == 1) {
System.exit(0); // 關閉
}
}
});
//底部的發(fā)送信息框與鏈接按鈕
JPanel top = new JPanel(new FlowLayout());
top.add(tfSend); //發(fā)送文本
top.add(btSend); //發(fā)送按鈕
this.add(top, BorderLayout.SOUTH); //加載到底部
//頭部放連接服務的
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);
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
RocketMQ4.5.X 實現(xiàn)修改生產者消費者日志保存路徑
這篇文章主要介紹了RocketMQ4.5.X 實現(xiàn)修改生產者消費者日志保存路徑方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

