import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.JOptionPane;
public class Server {
private static int PORT = 8080;//默认端口号
private ServerSocket serverSocket ;
private ServerThread serverThread;//服务器线程
private boolean startServer = false;//判断服务器是否启动
private ArrayList<ClientThread> clients;//上线客户数组
private Graph sGraph;
public Server() throws IOException {//构造函数
this.sGraph = new Graph();
this.sGraph.initGraph("服务器");
this.sGraph.Frame.addWindowListener(new WindowAdapter() {//关闭窗口时关闭服务器
public void windowClosing(WindowEvent e) {
if (startServer) {
try {
closeServer();
} catch (IOException e1) {
e1.printStackTrace();
}// 关闭服务器
}
System.exit(0);// 退出程序
}
});
this.sGraph.Button1.addActionListener(new ActionListener() {//启动服务器触发
public void actionPerformed(ActionEvent e) {
if(startServer){
JOptionPane.showMessageDialog(sGraph.Frame, "服务器已处于启动状态,请勿重复启动!", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
else{
try {
serverStart();
} catch (IOException e1) {
e1.printStackTrace();
}
sGraph.TextArea2.append("服务器已成功启动!\r\n");
JOptionPane.showMessageDialog(sGraph.Frame, "服务器已成功启动!");
sGraph.Button1.setEnabled(false);
sGraph.Button2.setEnabled(true);
}
}
});
this.sGraph.Button2.addActionListener(new ActionListener() {//断开服务器触发
public void actionPerformed(ActionEvent e) {
if(startServer){
try {
closeServer();
} catch (IOException e1) {
e1.printStackTrace();
}
sGraph.Button1.setEnabled(true);
sGraph.Button2.setEnabled(false);
sGraph.TextArea2.append("服务器已断开!\r\n");
JOptionPane.showMessageDialog(sGraph.Frame, "服务器已断开!");
return;
}
else{
JOptionPane.showMessageDialog(sGraph.Frame, "服务器尚未启动!", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
});
this.sGraph.Button3.addActionListener(new ActionListener() {//发送按钮发送消息
public void actionPerformed(ActionEvent e) {
String toSomebady = sGraph.choice.getSelectedItem().toString();
sendMessage(toSomebady);//toSomebady判断接收方
}
});
this.sGraph.TextField4.addActionListener(new ActionListener() {//回车键发送消息
public void actionPerformed(ActionEvent e) {
String toSomebady = sGraph.choice.getSelectedItem().toString();
sendMessage(toSomebady);
}
});
}
public void serverStart() throws IOException{//启动服务器
clients = new ArrayList<ClientThread>();
serverSocket = new ServerSocket(PORT);
serverThread = new ServerThread(serverSocket);
serverThread.start();//服务器线程
startServer = true;
}
@SuppressWarnings("deprecation")
public void closeServer() throws IOException{//关闭服务器
if(serverThread != null){
serverThread.stop();
}
for (int i = clients.size() - 1; i >= 0; i--) {
clients.get(i).getOut().println("CLOSE");//向客户线程发送关闭消息
clients.get(i).getOut().flush();
clients.get(i).stop();
clients.get(i).in.close();
clients.get(i).out.close();
clients.get(i).socket.close();
clients.remove(i);
}
if(serverSocket != null){
serverSocket.close();
}
sGraph.ListModel.removeAllElements();
startServer = false;
}
public void sendMessage(String toSomebady){//发送消息
if(this.startServer == false){
JOptionPane.showMessageDialog(sGraph.Frame, "服务器未启动,消息发送失败!", "错误", JOptionPane.ERROR_MESSAGE);
this.sGraph.TextField4.setText(null);
return;
}
if(clients.size() == 0){
JOptionPane.showMessageDialog(sGraph.Frame, "没有用户在线,消息发送失败!", "错误", JOptionPane.ERROR_MESSAGE);
this.sGraph.TextField4.setText(null);
return;
}
String message = this.sGraph.TextField4.getText();
if(message == ""){
JOptionPane.showMessageDialog(sGraph.Frame, "消息不能为空!", "错误", JOptionPane.ERROR_MESSAGE);
}
if(toSomebady.equals("群发")){//根据选择的接收方发送消息
this.sGraph.TextArea2.append("服务器 :" + message + "(群发)\r\n");
for (int i = clients.size() - 1; i >= 0; i--) {
clients.get(i).getOut().println("服务器 :" + message +"(群发)");
clients.get(i).getOut().flush();
}
}
else{
this.sGraph.TextArea2.append("服务器发送给" + toSomebady + " :" + message + "\r\n");
for (int i = clients.size() - 1; i >= 0; i--) {
if(clients.get(i).getUser().getName().equals(toSomebady)){//查找客户线程中的接收方
clients.get(i).getOut().println("服务器发送给" + toSomebady + " :" + message);
clients.get(i).getOut().flush();
}
}
}
this.sGraph.TextField4.setText(null);
}
class ServerThread extends Thread {//服务器线程
private ServerSocket serverSocket;
public ServerThread(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
@SuppressWarnings("unchecked")
public void run(){
while(true){
try {
Socket socket = serverSocket.accept();
ClientThread client = new ClientThread(socket);
client.start();//开启此客户端线程
clients.add(client);
sGraph.ListModel.addElement(client.getUser().getName());//在线用户列表增加客户
sGraph.choice.addItem(client.getUser().getName());//显示上线消息
sGraph.TextArea2.append(client.getUser().getName() + client.getUser().getIP()+"上线!\r\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ClientThread extends Thread{//客户线程
private Socket socket;
private BufferedReader in;
private PrintStream out;
private User user;
public ClientThread(Socket socket) throws IOException{
this.socket = socket;
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
out = new PrintStream(this.socket.getOutputStream());
String info = in.readLine();
StringTokenizer infoTemp = new StringTokenizer(info, "@");
user = new User(infoTemp.nextToken(), infoTemp.nextToken());
out.println(user.getName() + user.getIP() + "与服务器连接成功!\r\n");
out.flush();
if (clients.size() > 0){ //给客户端发命令
String temp = "";
for (int i = clients.size() - 1; i >= 0; i--){
temp += (clients.get(i).getUser().getName() + "/" + clients.get(i).getUser().getIP()) + "@";
}
out.println("USERLIST@" + clients.size() + "@" + temp);
out.flush();
}
for (int i = clients.size() - 1; i >= 0; i--) {
clients.get(i).getOut().println("ADD@" + user.getName() + user.getIP());
clients.get(i).getOut().flush();
}
}
public BufferedReader getIn(){
return in;
}
public PrintStream getOut(){
return out;
}
public User getUser(){
return user;
}
@SuppressWarnings("deprecation")
public void run(){
String message = null;
while(true){
try {
message = in.readLine();
if(message.equals("CLOSE")){//客户端断开连接
sGraph.TextArea2.append(this.getUser