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

📄 denglu.java

📁 用java实现网络用户机与服务器的连接。用户通过登陆用户端的界面
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

public class DengLu extends JFrame {
	private JTextArea  question;
	private JRadioButton buttons[];
	private final String names[]={"A.","B.","C.","D."};
    private ButtonGroup examGroup;  
    private JButton enterbutton,overButton,upButton,downButton;  
    private final int rights[]=new int[5];
    private static String reflect;
    private static String Que[] = new String[100];
    private static int key[] = new int[20];
    private static String Opt[][] = new String[100][4]; 
    private ObjectOutputStream output; 
	private ObjectInputStream input;
    private int m;     //记录总的考题数目
    private int n = 0;		//记录当前显示的题目号
	private JLabel namelable,codelable,ptlable;
	private JTextField nametext;
	private JPasswordField codetext;
	private Icon pt;
	final Container container=getContentPane();
	private String message,message1;		//接收响应信息
	private Socket toServer;//socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。
	                         //应用程序通常通过"套接字"向网络发出请求或者应答网络请求。
    
    //获取本机IP地址
	//public static final String IP = new String("InetAddress.getLocalHost().getHostAddress()");
	public static final String IP = "219.229.96.9";
	public static final int IPORT = 8888;  // 侦听端口
	//1-1023端口已被系统预先占用,应选用1024-65535端口,以免发生端口冲突。
	
	
	public DengLu() 
	{
		setTitle( "用户登陆" );
		container.setLayout(null);
		
		Icon pt = new ImageIcon("picture\\pt.gif");
		JLabel pti = new JLabel(pt);
        pti.setBounds(0,0,250,144);
        container.add(pti);
        
        namelable = new JLabel("用户名");
        namelable.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        namelable.setBounds(0,150,75,25);
        container.add(namelable);
        
        nametext = new JTextField();
        nametext.setBounds(83,150,130,25);
        container.add(nametext);
        
        codelable = new JLabel("密  码");
        codelable.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        codelable.setBounds(0,180,75,25);
        container.add(codelable);
        
        codetext = new JPasswordField();
        codetext.setBounds(83,180,130,25);
        container.add(codetext);
        
        enterbutton = new JButton("登陆答题系统");
        enterbutton.setBounds(83,220,130,25);
        //enterbutton.addActionListener(this);
        container.add(enterbutton);
        
        setSize (255, 300);
	    setDefaultCloseOperation(EXIT_ON_CLOSE);
	    setVisible(true);
	    
	    //设置对话框在屏幕正中间
		Toolkit tk = this.getToolkit(); 
		Dimension dm = tk.getScreenSize();
		int width = 255;
		int heigth = 300;
		setLocation((int)(dm.getWidth()-width)/2,(int)(dm.getHeight()-heigth)/2);

	    enterbutton.addActionListener(new ActionListener()
        { 
	        public void actionPerformed(ActionEvent event)
			{
				
				Customer data = new Customer();
	        	String user = nametext.getText().trim();  //返回字符串的副本,忽略前导空白和尾部空白。
	        	String psw = codetext.getText().trim();
	        	
	        	data.setCustomer(user,psw);
	        	//连接到服务器
	        	try
	        	{	
		  		   	toServer = new Socket(IP,IPORT);    //建立连接
			   	
		            System.out.println("客户端启动!");
		            
				   	final ObjectOutputStream output=new ObjectOutputStream (toServer.getOutputStream());
				   	//. getOutputStream方法连接的另一端将得到输入,同时返回一个OutputStream对象实例。					
				   	
				   	output.writeObject((Customer)data);//写客户详细资料到服务器socket  
				   	
		           	final ObjectInputStream input=new ObjectInputStream(toServer.getInputStream());
		           	//读来自服务器socket的登录状态. getInputStream方法获得网络连接输入,同时返回一个IutputStream对象实例
		           	 
		           	String status=input.readLine();
		
		           	JOptionPane.showMessageDialog(null,status);
	           	    
	           	       try 
					   {
							message = ( String ) input.readObject(); 
							System.out.println(message);
						}
						catch ( ClassNotFoundException classNotFoundException ) 
						{
									System.out.println("\nUnknown object type received" );
			  					}	
							    
						if(message.equals("请求通过,进入答题系统"))
						{
				            try		
			    		 	{
							    int d = Integer.parseInt((String)input.readObject());
							    m=d;
								for(int i=0;i<m;i++)
								{
									Que[i]  = ( String ) input.readObject();
								}
								for(int i=0;i<m;i++)
								for(int j=0;j<4;j++)
								{
									Opt[i][j] = ( String ) input.readObject();
								}
							}
							catch ( ClassNotFoundException classNotFoundException ) 
							{
								System.out.println("\nUnknown object type received" );
							}
							setVisible(false);
						    container.removeAll();		//从此容器中移除所有组件
						    setTitle( "答题系统" );	       
						    	 		 	
						   	JPanel p0=new JPanel(new GridLayout());
					        JPanel p1=new JPanel(new GridLayout(4,1));
					        JPanel p2=new JPanel(new GridLayout(1,3,10,0));
					        p0.setBounds(10,10,400,200);
					        p1.setBounds(10,210,400,100);
					        p2.setBounds(10,320,400,30);
					        container.add(p0);
					        container.add(p1);
					        container.add(p2);              
					
					        
					        question=new JTextArea();
					        question.setText(Que[0]);
					        question.setEditable(false);
					        JScrollPane jsp=new JScrollPane(question); 
					        p0.add(jsp);
					          
					        buttons=new JRadioButton[4];
					        examGroup=new ButtonGroup(); 
					         
					        RadioHandler radio=new RadioHandler(); 
					        for(int i=0;i<4;i++)
					        {
					            buttons[i]=new JRadioButton(Opt[m][i]);
					            buttons[i].setText(names[i]+Opt[0][i]);
					            buttons[i].addItemListener(radio);
					            p1.add(buttons[i]);         
					            examGroup.add(buttons[i]);	
					        }          
					               
					        overButton=new JButton("交    卷");

					        overButton.addActionListener(new ActionListener()
       						 { 
					         	public void actionPerformed(ActionEvent e)
						        {
						        	JOptionPane object=new JOptionPane();
						        	
						        	int  y=object.showConfirmDialog(null,"确定交卷吗?");
						        	if(y==object.YES_OPTION)
						        	{
						        		try
									    {
												for(int i=0;i<m;i++)
												{
													//System.out.println(rights[i]);
													output.writeObject(""+rights[i]); 
													output.flush();
												}
												try
								        		{
								        				
								        			output.writeObject("客户答题结束,请返回客户作答情况!");
								        			
									        		message1 = ( String ) input.readObject(); 
													System.out.println(message1);
													//System.out.println("11111");
													output.close();
													input.close();
													toServer.close();
												}catch ( ClassNotFoundException classNotFoundException ) 
												{
													System.out.println("\nUnknown object type received" );
					  							}catch ( IOException ioException ) 
											    {
											        ioException.printStackTrace();
											    }
												output.close();
												input.close();
												toServer.close();					
										}
										catch ( IOException ioException ) 
										{
											ioException.printStackTrace();
										}	
						        		 System.exit(0);
						        		
						        		/*try
						        		{	
						        			output.writeObject("客户答题结束,请返回客户作答情况!");
							        		message1 = ( String ) input.readObject(); 
											System.out.println(message1);
										}catch ( ClassNotFoundException classNotFoundException ) 
										{
											System.out.println("\nUnknown object type received" );
			  							}catch ( IOException ioException ) 
									    {
									        ioException.printStackTrace();
									    } */	
						        	}
						        	/*if(y==1)
						        	{
						        		output.writeObject("客户答题结束,请返回客户作答情况!");
						        		try
						        		{	
							        		message1 = ( String ) input.readObject(); 
											System.out.println(message1);
										}catch ( ClassNotFoundException classNotFoundException ) 
										{
											System.out.println("\nUnknown object type received" );
			  							}catch ( IOException ioException ) 
									    {
									        ioException.printStackTrace();
									    } 	
						        	}*/
					        	  }
					        	});		
				
					        upButton=new JButton("上一题");
					        upButton.setEnabled(false);
					        upButtonHandler upbutton=new upButtonHandler();
					        upButton.addActionListener(upbutton);
					        downButton=new JButton("下一题");
					        downButtonHandler downbutton=new downButtonHandler();
					        downButton.addActionListener(downbutton);
						    p2.add(downButton);
						    p2.add(upButton);
					        p2.add(overButton);

					        setSize(430,400);
					        setVisible(true);
					        setResizable(false);
	
						}
						else
						{
							System.out.println( "发送请求未成功!");
						}
						/*if(message.equals("finish"))
					   {
				            try		
					 		{
				 				reflect  = ( String ) input.readObject();
				 				System.out.println(reflect);
				 			}
				 			catch ( ClassNotFoundException classNotFoundException ) 
							{
								System.out.println("\nUnknown object type received" );
							}
						}*/
					}
					catch(ConnectException e1)
			        {
			         	JOptionPane.showMessageDialog(null,"服务器未启动!!!");
			        }
				    catch ( IOException ioException ) 
				    {
				        ioException.printStackTrace();
				    } 
				   }
		   });
		   
		   
	}	

	private class RadioHandler implements ItemListener
    {
    	public void itemStateChanged(ItemEvent e)
        {
        	for(int i=0;i<4;i++)
        	{
        		if(e.getSource()==buttons[i])
        			rights[n]=i+1;
        	}
        }    	
    }   
 
    	
    private class upButtonHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent e)
        {
        	if(n==0) upButton.setEnabled(false);
        	else
        	{
	        	n--;
	        	examGroup.clearSelection();//1.6版本。清除选中内容,从而没有选择 ButtonGroup 中的任何按钮。
	        	question.setText( Que[ n ] );//更新题目
	        	
	        	for(int i=0;i<4;i++)
	        	{
	        		buttons[i].setText(names[i]+Opt[n][i]);
	        	}
	        	downButton.setEnabled(true);
	        }
        }    	
    }   
    	
    private class downButtonHandler implements ActionListener
    {
    	public void actionPerformed(ActionEvent e)
        {
        	if(n==4) downButton.setEnabled(false);
        	else
        	{
	        	n++;
	        	examGroup.clearSelection();
	        	question.setText( Que[ n ] );
	        	
	        	for(int i=0;i<4;i++)
	        	{
	        		buttons[i].setText(names[i]+Opt[n][i] );
	        	}
	        	upButton.setEnabled(true);
	        }
    	}
    }    	

	
	public static void main(String args[]) 
    { 
        /*DengLu DL=new DengLu();
        DL.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );*/
        try 
    	{ 
	        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
        } 
      	catch (Exception exception)  
        {  
        	exception.printStackTrace();  
        }
        
        DengLu DL=new DengLu();         
    }
}

   	
   	
 /*try-catch用法和含义
 
try {   [tryStatements]} catch(exception) {   [catchStatements]} finally {   [finallyStatements]}

参数

tryStatements 可选。可能发生错误的语句。
exception 必选。任何变量名称。exception 的初始值是引发的错误的值。
catchStatements 可选。处理在相关联的 tryStatement 中发生的错误的语句。
finallyStatements 可选。在所有其他的错误过程发生之后被无条件执行的语句。

备注

try...catch...finally 语句提供了一种方法,可处理给定代码块中可能会发生的一些或全部错误,同时仍保持代码的运行。
如果发生了程序员没有处理的错误,JScript 只给用户提供它的一般错误信息,就好象没有错误处理一样。

tryStatements 参数包含可能发生错误的代码,而 catchStatement 则包含了可处理任何发生的错误的代码。
如果在 tryStatements 中发生了一个错误,则将把程序控制传递给 catchStatements 来处理该错误。
exception 的初始值是发生在 tryStatements 中发生的错误的值。如果不发生错误,则不执行 catchStatements。

如果在与发生错误的 tryStatements 相关联的 catchStatements 中不能处理该错误,
则使用 throw 语句将这个错误传播或重新引发给更高级的错误处理程序。

在执行完 tryStatements 中的语句,并在 catchStatements 的所有错误处理发生之后,可无条件执行 finallyStatements 中的语句。

请注意,即使 try 或 catch 块中出现返回语句,或 catch 块中引发错误,都会执行 finallyStatements 中的代码。
finallyStatments 一定会始终运行。*/


 

⌨️ 快捷键说明

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