第一步:建立一个服务器,多个客户端。Form控制表单,MG控制信息发送接收,Listener监听,Thread多个线程,也就是多个客户端。
ServerForm代码块:
package GUISocket.chat.Server;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.EventQueue;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ServerForm extends JFrame {
/**
*
*/
private JPanel contentPane;
public JTextArea textLog;
private JTextField textPort;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ServerForm frame = new ServerForm();
frame.setVisible(true);
ServerMG.getServerMG().setServerForm(frame);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public ServerForm() {
setTitle("多人聊天服务器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 510, 566);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("配置信息");
lblNewLabel.setBounds(20, 10, 54, 15);
contentPane.add(lblNewLabel);
JLabel label = new JLabel("端口:");
label.setBounds(30, 34, 39, 15);
contentPane.add(label);
textPort = new JTextField();
textPort.setText("8900");
textPort.setBounds(65, 31, 66, 21);
contentPane.add(textPort);
textPort.setColumns(10);
JButton btnStart = new JButton("开启服务");
btnStart.addActionListener(new BtnStartActionListener());
btnStart.setBounds(180, 30, 93, 23);
contentPane.add(btnStart);
JButton btnClose = new JButton("关闭服务");
btnClose.addActionListener(new BtnCloseActionListener());
btnClose.setBounds(325, 30, 93, 23);
contentPane.add(btnClose);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 474, 54);
contentPane.add(panel);
panel.setLayout(null);
JLabel label_1 = new JLabel("消息记录");
label_1.setBounds(10, 94, 54, 15);
contentPane.add(label_1);
JPanel panel_1 = new JPanel();
panel_1.setBounds(0, 81, 474, 436);
contentPane.add(panel_1);
panel_1.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 41, 464, 368);
panel_1.add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
textLog = new JTextArea();
textLog.setLineWrap(true);
textLog.setWrapStyleWord(true);
scrollPane.setViewportView(textLog);
}
private class BtnCloseActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
}
}
private class BtnStartActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//开启服务
int port=Integer.parseInt(textPort.getText().trim());
if(ServerMG.getServerMG().CreateServer(port)) {
ServerMG.getServerMG().setLogTxt("服务器开启...");
}
else {
ServerMG.getServerMG().setLogTxt("服务器开启失败...");
}
}
}
}
ServerListener代码块:
package GUISocket.chat.Server;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerListener extends Thread{
Socket socket=null;
ServerSocket server=null;
public ServerListener(ServerSocket server) {
this.server=server;
}
public void run() {
try {
while(true) {
socket=server.accept();
ServerMG.getServerMG().setLogTxt("客户端: "+socket);
new SocketThread(socket).start();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
ServerMG代码块:
package GUISocket.chat.Server;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JTextArea;
public class ServerMG {
private static final ServerMG servermg=new ServerMG();
private ServerMG() {}
public static ServerMG getServerMG() {
return servermg;
}
//主界面的操作
private ServerForm serverWin;
//将窗体对象注册到管理类当中
public void setServerForm(ServerForm s) {
serverWin=s;
}
//设置主界面
public void setLogTxt(String str) {
serverWin.textLog.append(str+"\r\n");
}
private ServerSocket server;
public boolean CreateServer(int port) {
try {
server=new ServerSocket(port);
new ServerListener(server).start();
return true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return false;
}
}
}
ServerThread代码块:
package GUISocket.chat.Server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketThread extends Thread{
BufferedReader br=null;
PrintWriter pw=null;
Socket socket=null;
public SocketThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
br=new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8")));
String str="";
while((str=br.readLine())!=null) {
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(pw!=null)
pw.close();
if(br!=null)
br.close();
if(socket!=null)
socket.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
public void closeChat() {
try {
if(pw!=null)
pw.close();
if(br!=null)
br.close();
if(socket!=null)
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMsg(String str) {
pw.println(str);
pw.flush();
}
}
ClientForm代码块:
package GUISocket.chat.Client;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.EventQueue;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ClientForm extends JFrame {
private JPanel contentPane;
DefaultListModel<String> itemUsers;
private JTextField textIP;
private JTextField textPort;
public JTextField textUser;
public JTextArea textLog;
public JTextArea textArea_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClientForm frame = new ClientForm();
frame.setVisible(true);
ClientMG.getClientMG().setClientForm(frame);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public ClientForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 589, 607);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("配置信息");
label.setBounds(10, 10, 54, 15);
contentPane.add(label);
JLabel lblIp = new JLabel("IP");
lblIp.setBounds(10, 35, 27, 15);
contentPane.add(lblIp);
textIP = new JTextField();
textIP.setText("192.168.1.10");
textIP.setBounds(33, 35, 92, 21);
contentPane.add(textIP);
textIP.setColumns(10);
JLabel label_1 = new JLabel("端口");
label_1.setBounds(137, 35, 38, 15);
contentPane.add(label_1);
textPort = new JTextField();
textPort.setText("8900");
textPort.setBounds(168, 32, 66, 21);
contentPane.add(textPort);
textPort.setColumns(10);
JLabel label_2 = new JLabel("用户名");
label_2.setBounds(255, 38, 54, 15);
contentPane.add(label_2);
textUser = new JTextField();
textUser.setBounds(302, 35, 66, 21);
contentPane.add(textUser);
textUser.setColumns(10);
JButton btnLogin = new JButton("登录");
btnLogin.setBounds(395, 34, 66, 23);
contentPane.add(btnLogin);
JButton btnClose = new JButton("关闭");
btnClose.setBounds(480, 31, 71, 23);
contentPane.add(btnClose);
JPanel panel = new JPanel();
panel.setBounds(0, 10, 573, 61);
contentPane.add(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(0, 81, 573, 369);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel label_3 = new JLabel("聊天记录");
label_3.setBounds(10, 10, 54, 15);
panel_1.add(label_3);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBounds(20, 35, 323, 324);
panel_1.add(scrollPane);
textLog = new JTextArea();
textLog.setWrapStyleWord(true);
textLog.setLineWrap(true);
scrollPane.setViewportView(textLog);
JLabel label_4 = new JLabel("在线用户");
label_4.setBounds(351, 10, 54, 15);
panel_1.add(label_4);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(353, 35, 210, 324);
panel_1.add(scrollPane_1);
textArea_1 = new JTextArea();
scrollPane_1.setViewportView(textArea_1);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 449, 553, 119);
contentPane.add(panel_2);
panel_2.setLayout(null);
JLabel label_5 = new JLabel("操作");
label_5.setBounds(10, 10, 54, 15);
panel_2.add(label_5);
JScrollPane scrollPane_2 = new JScrollPane();
scrollPane_2.setBounds(10, 22, 533, 64);
panel_2.add(scrollPane_2);
JTextArea textArea_2 = new JTextArea();
textArea_2.setWrapStyleWord(true);
textArea_2.setLineWrap(true);
scrollPane_2.setViewportView(textArea_2);
JButton button_1 = new JButton("群发");
button_1.setBounds(307, 86, 93, 23);
panel_2.add(button_1);
JButton sendMG = new JButton("发送");
sendMG.setBounds(432, 86, 93, 23);
panel_2.add(sendMG);
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//连接服务器user
String IP=textIP.getText().trim();
int port=Integer.parseInt(textPort.getText().trim());
String user=textUser.getText().trim();
if(ClientMG.getClientMG().Connect(IP,port,user)) {
ClientMG.getClientMG().setLogTxt("已经连接到服务器", user);
}
else {
ClientMG.getClientMG().setLogTxt("连接服务器失败", user);
}
}
});
}
}
ClientMG代码块:
package GUISocket.chat.Client;
import java.net.Socket;
public class ClientMG {
private static final ClientMG clientmg=new ClientMG();
private ClientMG() {}
public static ClientMG getClientMG() {
return clientmg;
}
private ClientForm clientWin;
public void setClientForm(ClientForm c) {
clientWin=c;
}
public void setLogTxt(String str,String user) {
clientWin.textLog.append(str+"\r\n");
clientWin.textArea_1.append(user);
}
SocketThread sthd;
public boolean Connect(String IP,int port,String user) {
Socket socket=null;
try {
socket=new Socket(IP,port);
SocketThread sthd=new SocketThread(socket, user);
sthd.start();
return true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return false;
}
}
}
SocketThread代码块:
package GUISocket.chat.Client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketThread extends Thread{
BufferedReader br=null;
PrintWriter pw=null;
Socket socket=null;
public SocketThread(Socket socket,String user){
super(user);//登录时用的用户名
this.socket=socket;
}
public void run() {
try {
br=new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8")));
String str="";
while((str=br.readLine())!=null) {
ClientMG.getClientMG().setLogTxt(str, str);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
if(pw!=null)
pw.close();
if(br!=null)
br.close();
if(socket!=null)
socket.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
public void sendMsg(String str) {
pw.println(str);
pw.flush();
}
}
实现结果如图: