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

📄 server.java

📁 一个简单的C/S模式考试系统
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.List;
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 bg = new Color(244,255,254);//定义一种颜色
	private String rightNow;	
	private InetAddress svrAddress;
	private ServerSocket server;
	private ServerThread st;
	static int m=0;
	static String t1;
	private Hashtable ht;//用于记录登陆考生的哈希表
	private Hashtable htr;//用于记录已交卷的哈希表
	private Hashtable htd;//用于记录登陆考生的验证信息
	private Hashtable htcorrect;//用于记录正确的试题答案的类	
    String dbname="test";
    String user1="sa";
    String pass="123456";
    String db="sqlserver";
    
	private Label svrIP = new Label("服务器 IP:");
	private TextField showSvrIP = new TextField();
	private Label svrPort = new Label("服务器端口:");
	private TextField getSvrPort = new TextField("5500");
	private Button enter = new Button("启动");
	private TextArea output = new TextArea();
	private Label user = new Label("考生数 (0)");//用来显示用户个数
	private List list = new List();
	private Button b1 = new Button("配置考生表");
	private Button b2= new Button("查看成绩");
	private Button b3 = new Button("查看日志");
	private Button b4 = new Button("清屏");
	private Button b5 = new Button("退出");
	private Button b7= new Button("配置题库");
	
		// 布局设置方法,在构造方法里面调用
	private void setup()
	{		
		Panel top = new Panel();
		top.setLayout(new FlowLayout());
		top.add(svrIP);
		svrIP.setBackground(bg);
		top.add(showSvrIP);
		showSvrIP.setBackground(bg);
		top.add(svrPort);
		svrPort.setBackground(bg);
		top.add(getSvrPort);
		getSvrPort.setBackground(bg);
		top.add(enter);
		enter.setBackground(bg);
		
		Panel east = new Panel();
		east.setLayout(new BorderLayout());
		east.add("North", user);
		user.setBackground(bg);
		east.add("Center", list);
		list.setBackground(bg);
		
		Panel south = new Panel();
		south.setLayout(new GridLayout(2,3));
		south.add(b1);south.add(b7);
		south.add(b2);
		south.add(b3);
		south.add(b4);
		south.add(b5);
		
		setLayout(new BorderLayout());
		add("North", top);
		top.setBackground(bg);
		add("East", east);
		east.setBackground(bg);
		add("Center", output);
		south.setBackground(bg);
			add("South", south);
		south.setBackground(bg);	
		
		setBackground(bg);
	}
	// 构造方法
	public Server(String dbname,String user2,String pass,String db)throws UnknownHostException,SocketException, EOFException
	{
		super("考试系统服务器端");
		this.dbname=dbname.trim();
        this.user1=user2.trim();
        this.pass=pass.trim();
        this.db=db.trim();
		
		
		serving = false;
		svrAddress = InetAddress.getLocalHost();
		byte[] ip = svrAddress.getAddress();
		showSvrIP.setText((ip[0]&0xFF)+"."+(ip[1]&0xFF)+"."
				+(ip[2]&0xFF)+"."+(ip[3]&0xFF));

		showSvrIP.setEditable(false);
		output.setEditable(false);
		b1.addActionListener(this);
		b2.addActionListener(this);
		b3.addActionListener(this);
		b4.addActionListener(this);
		b5.addActionListener(this);
		b7.addActionListener(this);
		enter.addActionListener(this);
		
		
		setup();
		pack();
		setLocation(200,200);
		setSize(500, 400);
		show();
	}
	// 用于接收客户消息的线程类
	private class ServerThreadSingle extends Thread{
 private Socket connectToClient;//服务器端传送/接收数据的套接字
 private DataOutputStream outToClient;//向客户输出数据
 private DataInputStream inFromClient;//从客户读取数据
 private ReadTestFile readTestFile;//读开始文件对象
 private String selectedAnswer="";//存放用户发送的答案
 private String correctAnswer="";//存放正确的答案
 //static String t1;
 private String id;


 public ServerThreadSingle(Socket socket) {
   connectToClient=socket;
   try {
      readTestFile=new ReadTestFile(dbname,user1,pass,db);//读取试题文件内容的类对象
      inFromClient=new DataInputStream(connectToClient.getInputStream());
      outToClient=new DataOutputStream(connectToClient.getOutputStream());
           id="13";
   }
   catch(IOException e) {  }
  start();//启动线程
 }

private void socketClosing() { //关闭所有流
  try {
     inFromClient.close();
     outToClient.close();
     connectToClient.close();
  }
  catch(IOException e) { 
  System.out.println("异常,关闭Socket!");
  }
}

public void run() {
  String inStr=""; //接收客户端信息的字符串
  String outStr=""; //发送给客户端信息的字符串
  
  while(true) {
     try {
        
       inStr=inFromClient.readUTF();
       if(inStr.startsWith("考试确认"))
       {inStr=inStr.substring(inStr.indexOf('@')+1);
       System.out.print("考生"+id);
         for(Enumeration e = ht.keys(); e.hasMoreElements();){
							String str = (String)(e.nextElement());
							if(str.equalsIgnoreCase(inStr)){
								outToClient.writeUTF("拒绝@");		//refused
								return;
							}  }
		 for(Enumeration e = htr.keys(); e.hasMoreElements();){
							String str = (String)(e.nextElement());
							if(str.equalsIgnoreCase(inStr)){
								String a=htr.get(inStr).toString();
								outToClient.writeUTF("成绩@"+a);		//refused
								return;
							}  }
		 										
       exec1 in=new exec1(inStr,dbname,user1,pass,db);
       String bu=in.print();
        t1=in.getTime();
        in.stop();
        
       outToClient.writeUTF("考试确认信息@"+bu);
       break;
       	}
       
       if(inStr.startsWith("开始考试")) {
         id=inStr.substring(inStr.indexOf('@')+1);
         for(Enumeration e = htd.keys(); e.hasMoreElements();){//检查是否正在验证
							String str = (String)(e.nextElement());
							if(str.equalsIgnoreCase(id)){
								outToClient.writeUTF("拒绝@");		//refused
								return;
							}  }
					htd.put(id,inFromClient);
         list.add(id);
         ht.put(id,inFromClient);
         m++;
         rightNow = Calendar.getInstance().getTime().toLocaleString();
					output.append(rightNow+"\n"+connectToClient.getInetAddress().toString()+"\n"+id+"号考生登陆\n");
         user.setText("考生数 ("+list.getItemCount()+")");
         String th="10";
        int time=Integer.parseInt(t1)*60*1000;
	  outToClient.writeUTF("考试时间@"+time+"@"+th);//接收客户点击"开始考试"按钮后,向客户发回考试时间
	  System.out.println(inStr); //显示考试开始
	   outStr=readTestFile.getTestQuestion("1",id);
	   htd.remove(id);
	   outToClient.writeUTF("下一题@"+outStr);
       }
       
     
    
	//接收客户点击"成绩"按钮后,向客户发回成绩
	 if(inStr.startsWith("成绩")) {
	String id=inStr.substring(inStr.indexOf('@')+1);
		selectedAnswer=id.substring(0,id.lastIndexOf('@'));
		id=id.substring(id.lastIndexOf("@")+1);
		id=id.trim();
		correctAnswer=readTestFile.getCorrectAnswer(id);
	   selectedAnswer=selectedAnswer.trim();
	   System.out.println("提交信息"+inStr);
	   System.out.println("选择题:"+selectedAnswer);
	   System.out.println("考号:"+id);
	   int score=getTestScore();
	   
	   if(score>=60) 
	       outStr="成绩"+score+"\n 祝贺你考试通过!";
	   else
	       outStr="成绩"+score+"\n 你考试没有通过!";
	   outToClient.writeUTF(outStr);
	   saveTestScore("testscore.log","成绩:"+score,id);
	   
	   System.out.println(outStr);
	  list.remove(id);
	  user.setText("考生数 ("+list.getItemCount()+")");
	rightNow = Calendar.getInstance().getTime().toLocaleString();//输出系统当前时间
	output.append(rightNow+"\n");//输出时间
	output.append(" "+id+" 号考生正常交卷"); 
	output.append(" 成绩:"+score+"\n"); 
	//isThere=id;System.out.println(isThere);
	ht.remove(id);
	htr.put(id,score);
	 break;
	}
	else{}
if(!serving) {
	outStr="停止";
	outToClient.writeUTF(outStr);
	socketClosing();
	break;}
    }
    catch(EOFException e2){
    	  
      
    	}
    	
    catch(SocketException e6) {
    	boolean sss=false;
      System.out.println("异常"+e6.toString());
       for(Enumeration e = htr.keys(); e.hasMoreElements();){
							String str = (String)(e.nextElement());
							if(str.equalsIgnoreCase(id)){
								sss=true;
								System.out.print("shi"+sss);
							return;									
																
																
							}  }
      if(!sss){
     System.out.print("263"+inStr.toString());
      list.remove(id);
      rightNow = Calendar.getInstance().getTime().toLocaleString();//输出系统当前时间
	output.append(rightNow+"\n");//输出时间
      output.append(" "+id+" 号退出"); 
	  user.setText("考生数 ("+list.getItemCount()+")");
      System.out.println("断开与客户连接");}
      socketClosing();//关闭所有流  
      break;//终止循环
    }
    catch(IOException e1){
    	System.out.print("io异常"+e1.toString());
    	}
  }		
	}
	private int getTestScore() { //计算分数
  
  String tishu="10";
  int n=0,testScore=0;
  String s=selectedAnswer;
  System.out.println("已选:"+selectedAnswer);
  correctAnswer=readTestFile.getCorrectAnswer(id);String c=correctAnswer;
  
   for(int i=Integer.parseInt(tishu);i>0;i--) {
   	 String s1=s.substring(0,s.lastIndexOf('@'));
   	 s=s.substring(s.lastIndexOf('@')+1);
   	 String c1=c.substring(0,c.lastIndexOf('@'));
   	  c=c.substring(c.lastIndexOf('@')+1);
   	  
   	  System.out.println(i+"已选答案"+s);System.out.println(i+"正确答案"+c);
   	 if(s.equals(c))
          n++;
    
       s=s1;c=c1;
  }
  testScore=(int)(100.0*n/Integer.parseInt(tishu));
  return testScore;
}

private void saveTestScore(String file,String score,String id) {//保存分数
  try {
    BufferedWriter scoreFile=new BufferedWriter(new FileWriter(file,true));//添加记录
    String ip=connectToClient.getInetAddress().toString();
    exec1 p=new exec1(id,dbname,user1,pass,db);
    String information=p.getName().trim();
    rightNow = Calendar.getInstance().getTime().toLocaleString();//输出系统当前时间
    scoreFile.write("考试时间"+rightNow+"考生机器ip:"+ip+"\n"+information);//把客户的IP地址写入到文件
    scoreFile.write("\n"+score);
    scoreFile.newLine();//换行
    scoreFile.flush();
    scoreFile.close();
    ScoreRecord sr=new ScoreRecord(dbname,user1,pass,db);
    sr.loadDatabase();
    score=score.substring(score.indexOf(':')+1);
    sr.setScore(id,score,ip,information);
    sr.stop();
  }
  catch(IOException e) {
    System.out.println("写成绩到文件发生异常");
    }
 }}
	// 用于接受客户连接请求的线程类
	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() == enter) 
		{
			if(serving){				
				try{
					
					serving = false;
					ht.clear();
					list.clear();
					user.setText("考生数 (0)");
					server.close();
					enter.setLabel("启动");				
				}catch(SocketException se){
					rightNow = Calendar.getInstance().getTime().toLocaleString();
					output.append(rightNow+"\n服务器停止.\n\n");
				}catch(IOException ioe){
					output.append("Error: "+ioe+"\n\n");
				}
			}
			else{	//首次登陆serving将为false进入此处理程序			
				try{
					server = new ServerSocket(Integer.parseInt(getSvrPort.getText()));//根据文本框的内容创建服务器端套结字
					rightNow = Calendar.getInstance().getTime().toLocaleString();//输出系统当前时间
					output.append(rightNow+"\n服务器启动.\n\n");//输出时间并显示系统启动
					enter.setLabel("停止");//同时将按钮置为停止以便停止
				    ht = new Hashtable();
				    htr=new Hashtable();
				    htd=new Hashtable();
				    htcorrect=new Hashtable();
					st = new ServerThread();//实例化serverThread的对象
					serving = true;
				}catch(IOException ioe){
					output.append("Error: "+ioe+"\n\n");
				}				
			}
		}
		if(event.getSource() ==b5){
			System.exit(0);}
	if(event.getSource()==b4){
		output.setText("");}
	
	if(event.getSource()==b3){
		ViewResult v1=new ViewResult();}
	if(event.getSource()==b2){
try{
	jt v=new jt(dbname,user1,pass,db);
}
catch(Exception ed){
	}
		}	
	if(event.getSource()==b1){
		JdbcDataConn1 thisApp=new JdbcDataConn1();
    
     thisApp.createInterFace(dbname,user1,pass,db);	}
     if(event.getSource()==b7){
		JdbcDataConn thisApp=new JdbcDataConn();
    
     thisApp.createInterFace(dbname,user1,pass,db);	}	
	
	}
	// 主方法
	//public static void main(String args [])throws UnknownHostException, IOException
	 //{
	 //	Server s = new Server("test","sa","123456","sqlserver");
//	 }

}

⌨️ 快捷键说明

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