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

📄 web158_com.java

📁 java socket 网上在线考试系统
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
                in = new DataInputStream(new FileInputStream(file));
                out = new DataOutputStream(clientSocket.getOutputStream());

                while ((length = in.read(buffer)) != -1) {
                        out.write(buffer, 0, length);
                }
                out.flush();
                in.close();
                out.close();
                System.out.println("文件发送完毕!");
                clientSocket.close();
               // return true;
        } catch (Exception e) {
                // TODO: handle exception
                System.out.println("错误:服务器没开启" + e);
                //return false;
        }//处理其它不可想问题
}
	//把考生的选择题题目写出
	public String getChoose()
	{
		String driver="sun.jdbc.odbc.JdbcOdbcDriver";
		String dbUrl="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=web158_exam/exam.dll";
		Statement stmt=null;
	 	Connection conn=null;
	 	//需要返回的记录集
	 	String returnStr="以下为考生"+stuname+"("+stuid+")的试卷备份"+System.getProperty("line.separator")+System.getProperty("line.separator");
		
		//加载驱动
		//**************************
		try
		{
			Class.forName(driver);
		}
		catch(java.lang.ClassNotFoundException nofound)
		{
			JOptionPane.showMessageDialog(null, "读取试卷时数据驱动错误");
			System.err.println(nofound.getMessage());
			return "error" ;
		}
		//开始添加试题	
		//**********************************
		try{
			conn=DriverManager.getConnection(dbUrl,"web158.com","web158.com");
			stmt=conn.createStatement();
			ResultSet rs=stmt.executeQuery("select * from exam");
			int rnum=0;
			String ok="";
			String s=System.getProperty("line.separator");
			while(rs.next())
			{
				String t=rs.getString("answer");
				String c=rs.getString("stuanswer");
				if(t.equals(c))
				{
					rnum++;
					ok="正确";
				}
				else
				{
					ok="错误";
				}
				returnStr+="第"+rs.getInt("id")+"题:"+s+s;
				returnStr+="    "+rs.getString("question")+s+s;
				returnStr+="    A:"+rs.getString("a")+s+s;
				returnStr+="    B:"+rs.getString("b")+s+s;
				returnStr+="    C:"+rs.getString("c")+s+s;
				returnStr+="    D:"+rs.getString("d")+s+s;
				returnStr+="    正确答案:"+t+"       考生所选答案:"+c+"             "+ok+s+s;
			}
			//操作题
			rs=stmt.executeQuery("select * from operate");
			//添加操作标题
			returnStr+=s+s+s+"以下为操作题,考生操作题答案在同文件夹中的answer.rar中:"+s+s+s;
			while(rs.next())
			{
				String t=rs.getString("id");
				String c=rs.getString("question");
				returnStr+="第"+t+"题:"+s+s+"    "+c+s+s;
			}
			//选择题正确
			returnStr+=s+s+"选择题正确题数:"+rnum+"              得分:"+rnum*prechoose+s+s+s;
			//把全局分数付值
			score=rnum*prechoose;
			//关闭连接
			stmt.close();
			conn.close();
			return returnStr;
		}//end of try
		catch(Exception ef)
		{
			JOptionPane.showMessageDialog(null, "考试交卷初始化选择题失败");
			System.out.println(ef.getMessage());
			return "error";
		}
		finally
		{
			try
			{
				stmt.close();
				conn.close();
			}catch(Exception ef)
			{}
			
		}
	} 
	//删除残余文件
	public void delExt()
	{
		try
		{
		File file;
		//先删除D盘中的系统文件
		deletefile("D:/myexam");
		//删除考生相关文件
		file=new File("web158_exam/exam.dll");
		if(file.exists())
		{
			file.delete();
		}
		file=new File("web158_exam/answer.dll");
		if(file.exists())
		{
			file.delete();
		}
		}
		catch(Exception ef)
		{
			System.out.print(ef.getMessage());
		}
	}
	//删除文件夹
	public void deletefile(String   delpath)   throws   FileNotFoundException,IOException   
	{   
		try   
		{   
			File   file   =   new   File(delpath);   
			if   (!file.isDirectory())   
			{   
				file.delete();   
			}   
			else if (file.isDirectory())   
			{   
				String[]   filelist   =   file.list();   
				for(int i = 0;i<filelist.length; i++)   
				{   
					File   delfile   =   new   File(delpath   +   "\\"   +   filelist[i]);   
				if   (!delfile.isDirectory())   
                delfile.delete();   
				else if (delfile.isDirectory())   
                deletefile(delpath+"\\"+filelist[i]);   
				}   
				file.delete();   
			}   
		}   
		catch   (FileNotFoundException  e)
		{ }      
	}  
	
	
	
	
	
	//启动服务器线程
	public String startClient(String ip,int port,String name,String id,int receiveport)
	{
		String str="";
		try
     	{
            System.out.println("正在与服务器建立连接...");
            socket = new Socket(ip,port); //建立和ServerSocket的连接
            System.out.println("连接已经建立");
            out = new PrintWriter(socket.getOutputStream(),true);
            //向服务器发送姓名,考号,命令
            out.println(name+"#"+id+"#"+"web158");
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println(in.readLine()); //按行输入
            String order=in.readLine();
            //服务器响应接收传来的文件
            if(order.equals("noexit"))
            {
            	JOptionPane.showMessageDialog(null, "您的考生信息不存在");
            	return "您的考生信息不存在";
            }
            //已经取过试题
            else if(order.equals("examed"))
            {
            	JOptionPane.showMessageDialog(null, "您的试题已经取过,请联系监考人员...");
            	return "你已经参加过考试";
            }
            //服务器出错
            else if(order.equals("error"))
            {
            	System.out.println("数据库出错");
            	JOptionPane.showMessageDialog(null, "服务器处理数据失败,请联系监考人员...");
            	return "服务器处理数据失败,请联系监考人员...";
            	
            }
            //服务器生成试卷失败
            else if(order.equals("cerror"))
            {
            	JOptionPane.showMessageDialog(null, "服务器生成随机试卷时失败,请联系监考人员...");
            	return "服务器生成随机试卷时失败,请联系监考人员...";
            }
            //服务器关闭
            else if(order.equals("closeed"))
            {
            	JOptionPane.showMessageDialog(null, "服务器已经关闭");
            	return "服务器已经关闭";
            }
            //服务器回复正在回发试题
            else if(order.equals("web158"))
            {
            	try
            	{
            		qpanel.top_info_text.setText("正在接收试卷...");
            		Thread.sleep(500);
            		clientReceive(ip,receiveport,"","","web158_exam/exam.dll");
            		qpanel.top_info_text.setText("正在接收考生身份信息...");
            		//接收图片数据
            		Thread.sleep(500);
            		clientReceive(ip,receiveport,"","","web158_com_skin/"+id+".dll");
            		System.out.print("文件接收成功");
            		str="文件接收成功";
            	}
            	catch(Exception ef)
            	{
            		System.out.print(ef.getMessage());
            		str="接收试题失败,请重试...";
            	}
            }
            //处理其它不可想情况
            else if(order.equals("othererror"))
            {
            	JOptionPane.showMessageDialog(null, "服务器出现未知错误");
            	return "服务器出现未知错误";
            }
            out.close();
            in.close();
            socket.close();
            str="试题提取成功";
            return str;
	     }
	     catch(IOException e)
	     	{
	         System.out.println("服务器没有开启"+e.getMessage()+ip+":"+port);
	         return "提取试题失败,与服务器:"+ip+":"+port+"建立连接失败...";
	         //return e.getMessage();
	     }
	     finally
	     {
	    	 try
	    	 {
	    	 socket.close();
	    	 out.close();
	    	 in.close();
	    	 }
	    	 catch(Exception ef)
	    	 {}
	     }
	}
	//接收文件
    public boolean clientReceive(String ip,int port,String name,String id,String filename){
        try{
                Socket clientSocket = new Socket(ip, port);
                DataInputStream in = new DataInputStream(clientSocket.getInputStream());

                File file = new File(filename);
                byte[] buffer = new byte[1024];
                int length = 0;
                
                if(!file.exists())
                        file.createNewFile();
                
                FileOutputStream fileOut = new FileOutputStream(file);
                
                while((length=in.read(buffer))!= -1){
                        fileOut.write(buffer, 0, length);                                
                }
                
                fileOut.close();
                clientSocket.close();
                return true;
        }catch (Exception e) {
                // TODO: handle exception
                System.out.println("总出错,老子火了 :" +e.getMessage());
                return false;
        }

}
	//
	void web158_info()
	{
//		取试题退出按钮事件
		qpanel.top_button_cancle.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				closetimer.start();
			}
		});
		//取试题确定按钮事件
		qpanel.top_button_ok.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
//				显示处理中
				qpanel.top_info_text.setText("系统处理中...");
				String host=qpanel.top_host_input.getText();
				int port=8888;
				try
				{
					port=Integer.parseInt(qpanel.top_port_input.getText());
					if(port<1000)
					{
						JOptionPane.showMessageDialog(null, "请输入数字类型端口号");
						qpanel.top_info_text.setText("端口号填写不正确");
						return;
					}
				}
				catch(Exception ef)
				{
					JOptionPane.showMessageDialog(null, "请输入数字类型端口号");
					qpanel.top_info_text.setText("端口号填写不正确");
					return;
				}
					//考生姓名考证号
				String name=qpanel.top_name_input.getText();
				//考生号码
				String id=qpanel.top_id_input.getText();
				//输入姓名和考号有注入信息
				if(name.indexOf("#")!=-1||name.indexOf("'")!=-1||id.indexOf("#")!=-1||id.indexOf("'")!=-1)
				{
					JOptionPane.showMessageDialog(null, "姓名和考号中请不要输入“'”或“#”");
					qpanel.top_info_text.setText("姓名和考号中请不要输入“'”或“#”");
					return;
				}
				//clientReceive(host,port,name,id);
				//启动服务器
				//是否初始化试题
				String str=startClient(host,port,name,id,receiveport);
				System.out.println(str);
				if(str.equals("试题提取成功"))
				{
					//把全局变量付值////////////////////////////////////////////////
					serverip=host;
					sendport=port;
					stuname=name;
					stuid=id;
					//初始化按钮////////////////////////////////////////////////////
					qpanel.top_info_text.setText("试题领取成功,点击确定开始答题");
						//添加新事件
					qpanel.top_begin.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) 
						{
							
							txtinfo.setText("注意:\n现在答的是第一大题:选择题\n请从A、B、C、D四个选项中选择出正确答案,点击上一题,下一题进行更改和答题");
							//试题面板
							getExamPanel();
							//计时
							timer.start();
							return;
						}
					});//end of actionPerformed
					qpanel.top_begin.setVisible(true);
					qpanel.top_button_ok.setVisible(false);
					qpanel.top_button_cancle.setVisible(false);
					//更新考生信息
					//头象
					headpic.setPicurl(id+".dll",name);
					headpic.setPreferredSize(new Dimension(120,150));
					pic_panel.removeAll();
					pic_panel.add(headpic);
					pic_panel.repaint();
					pic_panel.validate();
					//姓名
					web158_stu_name.setText("考生姓名:"+name);
					//全局变量付值
					
					//准考证号
					web158_stu_id.setText("准考证号:"+id);
					
					//把四个表彰不可用
					qpanel.top_id_input.setEnabled(false);
					qpanel.top_name_input.setEnabled(false);
					qpanel.top_host_input.setEnabled(false);
					qpanel.top_port_input.setEnabled(false);
					//写出考试说明
					txtinfo.setText("考生"+name+":\n\n请注意:\n试题已经发下!\n请点击开始答题进行答题!\n有不明白的问题请联系监考人员");
					//返回
					return ;
				}//取试题失败
				else
				{
					//qpanel.top_info_text.setText("试题领取失败,与服务器 "+host+":"+port+" 建立连接失败,请重试...");
					qpanel.top_info_text.setText(str);
					return ;
				}
			}
		});
		//以下更新信息
		web158_com_Cpanel.removeAll();
		web158_com_Cpanel.add(qpanel);
		web158_com_Cpanel.repaint();
		web158_com_Cpanel.validate();
		//m=m-1;
		//timer.start();
	}//end of web158_info

}//end of web158_frame


	/********************************************************
	 *                                                      *
	 *                  程序入口                             *
	 *                                                      *
	*********************************************************/
public class Web158_Com {
	
	//点位
	static Point origin = new Point();
	//主入口
	public static void main(String[] args) {
		/*
		//以下设置考生考试时不得做其它操作
		Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize(); //得到用户屏幕大小
		JFrame f=new JFrame();
		f.setSize(screenSize.width,screenSize.height);
		f.setUndecorated(true);
		f.setVisible(true);
		*/
		//创建窗口对象
		final web158_frame frame=new web158_frame();

		
		
		//添加窗口移动事件
		frame.addMouseListener (new MouseAdapter() {

			public void mousePressed(MouseEvent e) {

			origin.x = e.getX();origin.y = e.getY();

			}

		});//end of frame.addMouseListener ()
		//可以拖动
		
		frame.addMouseMotionListener(new MouseMotionAdapter() { 

			public void mouseDragged(MouseEvent e) {

			Point p = frame.getLocation();

			frame.setLocation(p.x + e.getX() - origin.x, p.y + e.getY() - origin.y );
			}

		});//end of frame.addMouseMotionListener()
		//添加最小化按钮
		frame.web158_com_system.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				frame.setExtendedState(Frame.ICONIFIED|frame.getExtendedState());
			}
		});
		
		//窗口移动事件完毕
	}

}

⌨️ 快捷键说明

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