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

📄 chat1.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 chat1  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 ServerSocket server;//此类实现服务器套接字。服务器套接字等待请求通过网络传入。它基于该请求执行某些操作,然后可能向请求者返回结果。 
    public Socket connection;//实现客户端套接字,套接字是两台机器之间的通信端点。
    public JScrollPane  helpwindow;//创建一个空的(无视口的视图)JScrollPane,需要时水平和垂直滚动条都可显示
    public JTextArea help;//跳出的帮助对话框
    
    
    public File fileName;
    
    public  ProgressMonitorInputStream pm;
    public JFrame myframe;
    
    public chat1 ()
    { 
    	fm=new JFrame("通信--用户1");
    	
        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() {//匿名类

    	            // 发送信息到chat2
    	            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();
					}
						
					
				}
		);
		
        b2=new JButton("接收文件");
        
      //  添加接受文件点击事件
		b2.addActionListener(
				
				new ActionListener() {
				
					public void actionPerformed(ActionEvent e) {
						
						try {
					          output.writeObject( "对方已准备接收,请发送..." );
					          
					          displayArea.append( "\n对方已准备接收,请发送..."  );
					          
					          
					       }

					       // 遇到I/O错误时
					       catch ( IOException ioException ) {
					          displayArea.append( "\nError writing object" );
					       }
						
						
							receiveFile();
							
					}
					
				}
		);
		
		
    	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 runchat1()//建立连接 
    {
     
        // 连接过程
        try {

           // 建立ServerSocket的对象
           server = new ServerSocket( 5000, 100 );//5000即为port值,是指定的端口;或者为 0,表示使用任何空闲端口.100为backlog的值,是输入连接指示(对连接的请求)的队列的最大长度
           
           while ( true ) {

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

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

    private void waitForConnection() throws IOException//等待建立连接
    {
       displayArea.setText( "正在连接中...\n" );

       // 接入连接
       connection = server.accept();//侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。
             
       displayArea.append( "连接到: " +connection.getInetAddress().getHostAddress());
    }

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

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

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

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

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

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

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

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

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

       } 
    }

   

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

       // 遇到I/O错误时
       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    receiveFile()   
    {   
            InputStream    slIn;   
            DataInputStream    dis;   
            DataOutputStream    dos=null;   
            try   
            {   
            	
                    File    file=new    File("e:\\a.txt");   
                    dos    =    new    DataOutputStream(new    FileOutputStream(file));   
            }   
            catch    (Exception    e)   
            {   
                    System.out.println(e);   
            }   
            while    (true)   
            {   
                    try   
                    {   
                    	    connection=server.accept();  
                            slIn    =   connection.getInputStream();    
                            dis    =    new    DataInputStream(slIn);   
                            byte[]    st    =    new    byte[1024];   
                            dis.read(st);   
                            dis.close();   
                            slIn.close();   
                            connection.close();   
                            if(new    String(st).startsWith("quit"))   
                                    break;   
                            dos.write(st);   
                            dos.flush();   
                    }   
                    catch    (Exception    e)   
                    {   
                            System.out.println(e);   
                    }   
            }   
            try   
            {   
                    dos.close();   
            }   
            catch    (Exception    ex)   
            {   
                    System.out.println(ex);   
            }   
    }   
    
   
    

    public static void main( String args[] )
	   {
	      chat1 application = new chat1();

	      application.setDefaultCloseOperation(
	         JFrame.EXIT_ON_CLOSE );

	      application.runchat1();
	      
	      
	      
	   }

    
}

⌨️ 快捷键说明

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