⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server.java

📁 Java实现的通讯录系统
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Calendar;

public class Server extends Frame implements ActionListener{
	
	private boolean serving = false;
	private Color backGround = new Color(255,255,255);
	private String rightNow;	
	private InetAddress serverAddress;
	private ServerSocket server;
	private ServerThread st;
	private Hashtable userHashTable;
	private Hashtable connectHashTable;

	private Label serverIP = new Label("本服务器IP地址:");
	private TextField printServerIP = new TextField();
	private Label serverPort = new Label("端口号:");
	private TextField getServerPort = new TextField("1234");
	private Button start = new Button(" 启动服务器 ");
	private Button end = new Button(" 停止服务器 ");
	private Label outputTitle = new Label("聊天记录:");
	private TextArea output = new TextArea();
	private Label user = new Label("在线成员(0)");
	private List list = new List();
	 
	// 响应关闭按钮的内部类
	private class WindowCloser extends WindowAdapter
	{
		public void windowClosing(WindowEvent we)
		{
			System.exit(0);
		}
	}
	// 窗口布局
	private void openWindow()
	{	
		Font fb = new Font("Helvetica", Font.BOLD, 17);
		Font fp = new Font("Courier", Font.PLAIN, 14);
		
		Panel north = new Panel();
		north.setLayout(new FlowLayout());
		north.add(serverIP);
		serverIP.setBackground(backGround);
		serverIP.setFont(fp);
		north.add(printServerIP);
		printServerIP.setBackground(backGround);
		north.add(serverPort);
		serverPort.setBackground(backGround);
		serverPort.setFont(fp);
		north.add(getServerPort);
		getServerPort.setBackground(backGround);
		
		Panel east = new Panel();
		east.setLayout(new BorderLayout());
		east.add("North", user);
		user.setBackground(backGround);
		user.setFont(fp);
		east.add("Center", list);
		list.setBackground(backGround);
		
		Panel center = new Panel();
		center.setLayout(new BorderLayout());
		center.add("North", outputTitle);
		outputTitle.setBackground(backGround);
		outputTitle.setFont(fp);
		center.add("Center", output);
		output.setBackground(backGround);
		
		Panel south = new Panel();
		south.setLayout(new FlowLayout());
		south.add(start);
		start.setBackground(new Color(192, 192, 192));
		start.setFont(fb);
		south.add(end);
		end.setBackground(new Color(192, 192, 192));
		end.setFont(fb);
		
		setLayout(new BorderLayout());
		add("North", north);
		north.setBackground(backGround);
		add("East", east);
		east.setBackground(backGround);
		add("Center", center);	
		add("South", south);
		setBackground(backGround);
	}
	// 构造方法
	public Server()throws UnknownHostException, IOException
	{
		super("多人聊天室服务器  Server");
		
		serving = false;
		serverAddress = InetAddress.getLocalHost();
		byte[] IP = serverAddress.getAddress();
		printServerIP.setText((IP[0]&0xFF)+"."+(IP[1]&0xFF)+"."
				+(IP[2]&0xFF)+"."+(IP[3]&0xFF));

		printServerIP.setEditable(false);
		output.setEditable(false);
		
		start.addActionListener(this);
		end.addActionListener(this);
		end.setEnabled(false);
		addWindowListener(new WindowCloser());
		
		openWindow();
		pack();
		setSize(500, 550);
		show();
	}
	// 用于接收客户消息的线程类
	private class ServerThreadSingle extends Thread{
		public Socket connection;
		private DataInputStream in;
		private DataOutputStream out;
		private boolean login;
		private String userName;
		public ServerThreadSingle(Socket newConnection){
			try{
				connection = newConnection;
				in = new DataInputStream(connection.getInputStream());
				out = new DataOutputStream(connection.getOutputStream());
				login = false;
				userName = new String("");
				start();				
			}catch(IOException ioe){
				output.append("Error: "+ioe);
			}			
		}
		public void run(){
			try{
				String line = new String("Q");
				while(!login){
					if(!serving) break;
					line = in.readUTF();
					if(line.charAt(0) == 'L'){						
						userName = line.substring(2);
						if(userName.length() == 0 ||userName.equalsIgnoreCase("请在此处输入您的名字")){
							out.writeUTF("R");	//refused
							break;
						}
						// 判断是否已存在该用户名
						for(Enumeration e =userHashTable.keys(); e.hasMoreElements();){
							String str = (String)(e.nextElement());
							if(str.equalsIgnoreCase(userName)){
								out.writeUTF("R");		//refused
								return;
							}
						}
						// 向登陆的用户发送当前在线用户列表
						login = true;
						list.add(userName);
						user.setText("在线成员 ("+list.getItemCount()+")");
						String[] str = list.getItems();
						line = "A ";				//accepted
						for (int i = 0; i < str.length; i ++){
							line += (str [i] + " ");
						}
						out.writeUTF(line);
						
						line = "L "+userName;
						rightNow = Calendar.getInstance().getTime().toLocaleString();
						output.append(rightNow+"\n!!!"+userName+" 上线.\n\n");
						// 向在线用户(不包括当前客户)发送消息
						for(Enumeration e =userHashTable.elements(); e.hasMoreElements();){
							DataOutputStream out = (DataOutputStream)(e.nextElement());
							out.writeUTF(line);
						}
						userHashTable.put(userName, out);	// 将登录的客户加入名单
						connectHashTable.put(userName, connection);
					}
				}
				//当用户退出时,该用户从名单中剔除
				while(login){
					line = in.readUTF();
					if(!serving) break;
					if(line.charAt(0) == 'Q'){
						out.writeUTF("Q");
						login = false;
						userHashTable.remove(userName);	
						connectHashTable.remove(userName);
						list.remove(userName);
						user.setText("在线成员 ("+list.getItemCount()+")");

						line = "Q "+userName;
					}
					else{
						line = userName+" 对大家说:\n"+line.substring(2);
					}
					rightNow = Calendar.getInstance().getTime().toLocaleString();
					output.append(rightNow+"\n"+(line.charAt(0)=='Q'?"!!!"+userName+"刚刚下线.":line)+"\n\n");
					// 向所有客户发送消息
					for(Enumeration e =userHashTable.elements(); e.hasMoreElements();){
						DataOutputStream out = (DataOutputStream)(e.nextElement());
						out.writeUTF(line);
					}		
				}
				in.close();
				out.close();
				connection.close();
			}catch(SocketException se){
				userHashTable.remove(userName);
				connectHashTable.remove(connection);
				list.remove(userName);
				output.append("!!!与 "+userName+" 断开连接\n");
			}catch(IOException ioe){
				if(!(ioe instanceof EOFException)){
					output.append("Error: "+ioe+"\n\n");
				}				
			}
		}		
	}
	// 用于接受客户连接请求的线程类
	private class ServerThread extends Thread{
		private boolean running;
		public ServerThread()
		{
			start();
		}
		public void run()
		{
			try{
				while(serving){
					Socket connection = server.accept();
					ServerThreadSingle handler
						= new ServerThreadSingle(connection);
				}
			}catch(SocketException se){
				rightNow = Calendar.getInstance().getTime().toLocaleString();
				output.append(rightNow+"\n!!!服务器停止.\n\n");
			}catch(IOException ioe){
				output.append("Error: "+ioe+"\n\n");
			}		
		}
	}
	// 消息处理方法
	public void actionPerformed(ActionEvent event){
		if(event.getSource() == end && serving) {				
			try{
				for(Enumeration e =userHashTable.elements(); e.hasMoreElements();){
					DataOutputStream out = (DataOutputStream)(e.nextElement());
					out.writeUTF("Q");					
				}
				serving = false;
				userHashTable.clear();
				connectHashTable.clear();
				list.clear();
				user.setText("在线成员 (0)");
				server.close();
				end.setEnabled(false);
				start.setEnabled(true);
			}catch(SocketException se){
				rightNow = Calendar.getInstance().getTime().toLocaleString();
				output.append(rightNow+"\n!!!服务器停止运行.\n\n");
			}catch(IOException ioe){
					output.append("Error: "+ioe+"\n\n");
			}
	    }
		else if(event.getSource() == start && !serving){				
			try{
	            server = new ServerSocket(Integer.parseInt(getServerPort.getText()));
				rightNow = Calendar.getInstance().getTime().toLocaleString();
				output.append(rightNow+"\n!!!服务器启动.\n\n");
				start.setEnabled(false);
				end.setEnabled(true);
				userHashTable = new Hashtable();
				connectHashTable = new Hashtable();
				st = new ServerThread();
				serving = true;
			}catch(IOException ioe){
				output.append("Error: "+ioe+"\n\n");
			}				
		}
	}
		
	
	
	// 程序入口
	public static void main(String args [])throws UnknownHostException, IOException
	{
		Server s = new Server();
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -