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

📄 chat2.java

📁 计算机网络的课程大作业,具有聊天和传送文件的功能.结构简单明了.
💻 JAVA
字号:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


import java.text.*;
import java.util.*;




public class chat2 extends JFrame{
	public JFrame fm;
    public JPanel p,p1;
	public JTextField  enterField;
	public JTextArea displayArea;
    public JButton b1,b2,b3;
	public JLabel lb;
	public ObjectOutputStream output;
	public ObjectInputStream input;
	public String message="";//此类实现服务器套接字。服务器套接字等待请求通过网络传入。它基于该请求执行某些操作,然后可能向请求者返回结果。
	
    public String chatServer;
	public Socket client;//实现客户端套接字,套接字是两台机器之间的通信端点。
	public JScrollPane  helpwindow;//创建一个空的(无视口的视图)JScrollPane,需要时水平和垂直滚动条都可显示
    public JTextArea help;//跳出的帮助对话框
    
    
    public File fileName;
    
    
    
    
    public chat2 (String host)
    { 
    	fm=new JFrame("通信--用户2");
    	chatServer = host;
    	
        p=new JPanel();//主面板
        fm.getContentPane().add(p);
    	p1=new JPanel();//放置按钮的面板
    	
    	p.setLayout(new BorderLayout());
    	
    	lb = new JLabel("设计者:计应0504 刘倩");
    	lb.setForeground(Color.blue);//设置显示计时字符的颜色
		p.add(lb,BorderLayout.NORTH);//标签居北,即在最顶部
    	
    	enterField=new JTextField(100);//输入区
    	enterField.setEnabled( false );//在未连接成功时,不能输入
    	enterField.setText("");
    	enterField.addActionListener(

    	         new ActionListener() {//匿名类

                //发送信息到chat1
    	            public void actionPerformed( ActionEvent event )
    	            {
    	               sendData( event.getActionCommand() );
    	              
    	            }

    	         }  

    	      ); 
    	

    	p.add(enterField,BorderLayout.SOUTH);//显示栏添加在中部
    	
    	displayArea = new JTextArea();//显示信息
    	p.add(new JScrollPane( displayArea ),BorderLayout.CENTER);//显示栏添加在中部
    	
    	
		
		b1=new JButton("选择文件");
		
        //	  添加打开文件点击事件
  		b1.addActionListener(
  				
  				new ActionListener() {
  				
  					public void actionPerformed(ActionEvent e) {
  						openFile();
  						try{
  						output.writeObject( "chat2要发送文件,请接收..."  );
  			          
  			          displayArea.append( "\nchat2要发送文件,请接收..." );
  			          
  						}
  						 catch ( IOException ioException ) {
  					          displayArea.append( "\nError writing object" );
  					       }
  						
  					}
  					
  				}
  		);
        b2=new JButton("传送文件");
        
   
        
        //      添加传送文件点击事件
  		b2.addActionListener(
  				
  				new ActionListener() {
  				
  					public void actionPerformed(ActionEvent e) {
  						
  						sendFile(); 
  						try{
  	  						output.writeObject( "传送完毕..."  );
  	  			          
  	  			          displayArea.append( "\n传送完毕...." );
  	  			          
  	  						}
  	  						 catch ( IOException ioException ) {
  	  					          displayArea.append( "\nError writing object" );
  	  					       }
  	  						
  					}
  					
  				}
  		);
  		
    	b3=new JButton("帮助");
    	help=new  JTextArea(5,20);//跳出的帮助窗口
		helpwindow=new JScrollPane(help);
		help.append("使用说明:\n");//追加指定字符,即在帮助窗口中的文字
		help.append("**发送消息使用步骤:\n");
		help.append("1.在窗口最下方输入要发送的信息\n");
		help.append("2.按回车键即为发送\n");
		help.append("**发送文件使用步骤:\n");
		help.append("1.先点击选择文件按钮,在磁盘上选择要发送的文件\n");
		help.append("2.\n");
		
    	b3.addActionListener(
    			 new ActionListener() {//匿名类

     	            // 为帮助按钮设置监听
     	            public void actionPerformed( ActionEvent event )
     	            {
     	            	JOptionPane.showMessageDialog(p,helpwindow);
     	              
     	            }

     	         }  

     	      ); 
    	
    	
    	
    	p1.setLayout(new GridLayout(3,1));
    	
    	p1.add(b1);
    	p1.add(b2);
    	p1.add(b3);
    	
    	p.add(p1,BorderLayout.EAST);//将按钮面板添加到东面即面板右侧
    	
    	
    	
        
		
		fm.setSize(400,300);
		fm.setVisible(true);
}
    public void runchat2()
    {
    	
    	
    	
       //  建立连接
        try {

           connectToServer();
           getStreams();
           
           processConnection();
           
           
           
       }

        // 输入过程中意外到达文件或流的末尾时
        catch ( EOFException eofException ) {
           System.out.println( "对方关闭连接..." );
        }

        // 遇到I/O错误
        catch ( IOException ioException ) {
           ioException.printStackTrace();
        }
    	
    }
    

    private void getStreams() throws IOException//输入输出信息流
    {
       // 建立输出流
       output = new ObjectOutputStream(client.getOutputStream() );

       
       output.flush();////刷新该流的缓冲,将写入所有已缓冲的输出字节,并将它们刷新到基础流中。 

       //  建立输入流
       input = new ObjectInputStream(client.getInputStream() );

       displayArea.append( "\n欢迎使用本系统\n" );//表明输入输出流已建立
    }

    // 与chat1进行连接
    private void connectToServer() throws IOException
    {      
       displayArea.setText( "接收到连接请求...\n" );

       // 建立给定主机名的 IP 地址连接
       client = new Socket( 
          InetAddress.getByName( chatServer ), 5000 );

       
       displayArea.append( "本机IP: " +
          client.getInetAddress().getHostAddress() );//显示返回连接到的主机 IP 地址
    }

     //  与chat1建立连接
    private void processConnection() throws IOException
    {
    	String message = "系统提示>>> 连接成功...";
    	
        output.writeObject( message );//将"系统提示>>> 连接成功..."输出
        output.flush();

       
       enterField.setEnabled( true );//使用户建立可以键入信息
       
       
       

       // 显示从用户1发来信息
       while(true) {

        //  将输入的信息显示
          try {
             message = ( String ) input.readObject();
             displayArea.append( "\n" + message );
             
             
             //displayArea.setCaretPosition(displayArea.getText().length() );
          
             
          }

          // 读入时遇到错误抛出
          catch ( ClassNotFoundException classNotFoundException ) {
             displayArea.append( "\nUnknown object type received" );
          }

       } 

    }  

    

    // 向用户1发信息
    private void sendData( String message )
    {
       
       try {
          output.writeObject( "chat2>>> " + message );
          output.flush();
          displayArea.append( "\nchat2>>>" + message );
          enterField.setText("");
       }

       // process problems sending object
       catch ( IOException ioException ) {
          displayArea.append( "\nError writing object" );
       }
    }
    
    public void openFile() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//允许用户只选择文件

		int result = fileChooser.showOpenDialog(this);//弹出一个 "Open File" 文件选择器对话框。

		// 如果选择窗口中的取消按钮,则窗口关闭,返回到聊天对话框
		if (result == JFileChooser.CANCEL_OPTION)
			return;

		// 选择文件
		fileName = fileChooser.getSelectedFile();
		
		}
    
    public    void    sendFile()   
    {   
            
             
            OutputStream    slout;   
            DataOutputStream    dos;   
            try   
            {   
                    DataInputStream    dis    =    new    DataInputStream(new    FileInputStream(fileName));   
                    byte[]    line=new    byte[1024];   
                    int    loop=dis.available()/1024+1;   
                    for(int    i=0;i<loop;i++)   
                    {   
                            dis.read(line);   
                            client   =    new    Socket(InetAddress.getLocalHost(),5000);   
                            slout    = client.getOutputStream();  
                            dos    =    new    DataOutputStream(slout);   
                            dos.write(line);   
                            Thread.sleep(50);   
                            dos.close();   
                            slout.close();   
                            client.close();    
                            line=new    byte[1024];   
                    }   
                    client =    new    Socket(InetAddress.getLocalHost(), 5000);   
                    slout    =client.getOutputStream();    
                    dos    =    new    DataOutputStream(slout);   
                    dos.write("quit".getBytes());   
                    dos.close();   
                    slout.close();   
                    client.close();
                    dis.close();   
            }   
            catch(Exception    e)   
            {   
                    System.out.println(e);   
            }   
    }   
    


    
    public static void main( String args[] )
    {
       chat2 application;

       if ( args.length == 0 )
          application = new chat2( "127.0.0.1" );
       else
          application = new chat2( args[ 0 ] );

       application.setDefaultCloseOperation(
          JFrame.EXIT_ON_CLOSE );

       application.runchat2();
       
      
    }
    
    
}
     

⌨️ 快捷键说明

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