基于C/S模式的简单聊天室
要求: 使用Socket实现网上聊天室,要求基于TCP或UDP协议,用户可以通过客户端连接到服务器端并进行聊天,聊天时可以启动多个客户端;服务器启动后,接收客户端发来的用户名和验证信息,验证通过则可以加入聊天室,当客户退出聊天时在聊天室公告改用户退出信息;要求界面美观。
- 运行结果
package client;
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.io.IOException;
import java.net.InetAddress;
import java.util.Vector;
import javax.swing.*;
public class ClientFrame extends JFrame {
JTextField field1;
JTextField usernamefield1;
JPasswordField passwordfield2;
JLabel label1;
JLabel label2;
JPanel panel;
JTextArea area;
JButton button;
String userName;
String passWord;
Vector<String> username = new Vector(6);
Vector<String> password = new Vector(6);
int flag;
boolean is_empty = true;
ChatRoomClient client;
public ClientFrame() {
setUser();
do {
try {
String host = InetAddress.getLocalHost().getHostAddress().toString();
if (host == null) {
System.exit(0);
}
client = new ChatRoomClient(host, 5678);
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "网络无法连接,请重新设置参数");
}
} while (client == null);
while(is_empty) {
field1 = new JTextField(25);
String str = JOptionPane.showInputDialog(this, "请输入用户名:");
userName = str.trim();
usernamefield1 = new JTextField(15);
label1 = new JLabel(userName);
String str2 = JOptionPane.showInputDialog(this, "请输入"+userName+"的密码:");
passWord = str2.trim();
passwordfield2 = new JPasswordField(15);
passwordfield2.setEchoChar('*');
label2 = new JLabel(passWord);
is_empty = is_empty(userName,passWord);
int yz = is_true(userName,passWord);
if(yz == 1) {
area = new JTextArea(20, 15);
area.setEditable(false);
button = new JButton("发送");
panel = new JPanel();
init();
addEventHandler();
}else {
if(is_empty == false) {
JOptionPane.showMessageDialog(null, "账号或密码错误,请重新输入", "提示", 1);
}
is_empty = true;
}
}
}
public boolean is_empty(String userName, String passWord) {
if(userName.length() == 0) {
is_empty = true;
JOptionPane.showMessageDialog(this, "用户名不能为空");
}else if(passWord.length() == 0){
is_empty = true;
JOptionPane.showMessageDialog(this, "密码不能为空");
}else {
is_empty = false;
}
return is_empty;
}
void setUser() {
username.add("张三");
username.add("李四");
username.add("王五");
password.add("zs123");
password.add("ls123");
password.add("ww123");
}
public void init() {
JScrollPane jsp = new JScrollPane(area);
this.setTitle(" 602聊天室");
this.add(jsp);
panel.add(label1);
panel.add(field1);
panel.add(button);
this.add(panel, BorderLayout.SOUTH);
}
public void showMe() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
new ReadMessageThread().start();
}
public int is_true(String userName,String passWord) {
flag = 0;
for(int i=0;i<username.size();i++) {
if(username.get(i).equals(userName) && password.get(i).equals(passWord)){
flag = 1;
}
}
if(flag == 1) {
JOptionPane.showMessageDialog(null, "登录成功", "提示", -1);
}
return flag;
}
public void addEventHandler() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(field1.getText().length() == 0) {
JOptionPane.showMessageDialog(null, "消息不能为空", "注意", 1);
is_empty = true;
}else {
is_empty = false;
}
if(is_empty == false) {
client.sendMessage(userName + ":" + field1.getText());
field1.setText("");
}
}
});
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent atg0) {
int op = JOptionPane.showConfirmDialog(ClientFrame.this,
"确定要退出聊天室吗?", "确定", JOptionPane.YES_NO_OPTION);
if (op == JOptionPane.YES_OPTION) {
client.sendMessage("%EXIT%:" + userName);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.close();
System.exit(0);
}
}
});
}
private class ReadMessageThread extends Thread {
public void run() {
while (true) {
String str = client.reciveMessage();
area.append(str + "\n");
}
}
}
public static void main(String[] args) {
new ClientFrame().showMe();
}
}
客户端
package client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;
import javax.swing.JOptionPane;
public class ChatRoomClient {
Socket s;
BufferedReader br;
PrintWriter pw;
public ChatRoomClient(String host, int port) throws UnknownHostException,
IOException {
s = new Socket(host, port);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream());
}
public void sendMessage(String str) {
pw.println(str);
pw.flush();
}
public String reciveMessage() {
try {
String xx = br.readLine();
return xx;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void close() {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
public class ChatRoomServer {
ServerSocket serversocket;
HashSet<Socket> allSockets;
public ChatRoomServer() {
try {
serversocket = new ServerSocket(5678);
} catch (IOException e) {
e.printStackTrace();
}
allSockets = new HashSet<Socket>();
}
public void startService() throws IOException {
System.out.println("服务器已成功开启");
while (true) {
Socket s = serversocket.accept();
System.out.println("用户已进入聊天室");
allSockets.add(s);
new ServerThread(s).start();
}
}
private class ServerThread extends Thread {
Socket s;
public ServerThread(Socket s) {
this.s = s;
}
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(
s.getInputStream()));
while (true) {
String str = br.readLine();
if (str.indexOf("%EXIT%") == 0) {
allSockets.remove(s);
sendMessageTOAllClient("-" + str.split(":")[1]
+ "-已退出聊天室");
s.close();
return;
}
sendMessageTOAllClient(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessageTOAllClient(String message) throws IOException {
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
System.out.println(message + "\t[" + df.format(date) + "]");
for (Socket s : allSockets) {
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println(message + "\t[" + df.format(date) + "]");
pw.flush();
}
}
}
public static void main(String[] args) {
try {
new ChatRoomServer().startService();
} catch (IOException e) {
e.printStackTrace();
}
}
}
需要详细报告或者有问题可以加QQ: 2953094905
|