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

📄 listeningserver.java

📁 一个简单的聊天程序
💻 JAVA
字号:
package chatdemo2;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class ListeningServer extends JFrame implements Runnable,ActionListener{
 Socket socket;
 JTextArea area=new JTextArea(20,30);
 JTextField input=new JTextField(30);
 JButton btn;
 boolean stop=true;
 PrintStream writer;
 DataInputStream reader;
  public ListeningServer(Socket socket)  {
    this.socket=socket;
    if(socket==null)
    JOptionPane.showMessageDialog(null,"socket is null");
    JPanel contentPane=(JPanel)this.getContentPane();
    contentPane.setLayout(new BorderLayout());
    contentPane.add(area,BorderLayout.CENTER);
    contentPane.add(input,BorderLayout.SOUTH);
    area.setEditable(false);
    input.addActionListener(this);
    try{
    reader=new DataInputStream(socket.getInputStream());
    writer=new PrintStream(socket.getOutputStream());
    }catch(Exception e){
      JOptionPane.showMessageDialog(null,"IO error");
    }
    this.pack();
    this.setVisible(true);
    ///////////////////////////



    //////////////////////

  }
  public void run(){

    try{
      while (true) {
        System.out.println("run begin");
        String temp = reader.readLine();
        if(temp==null) throw new Exception();
       System.out.println("server can read");
        getInfo(temp);

      }
    }catch(Exception e){
      JOptionPane.showMessageDialog(null,"client closed");
    }
  }

  public void actionPerformed(ActionEvent e){
      writer.println(input.getText());
      getInfo(input.getText());
      input.setText("");
      System.out.println("server input action worked");
  }
  public void getInfo(String str){
    StringBuffer temp=new StringBuffer(str+"\n");
    temp.append(area.getText());
    area.setText(temp.toString());

 }
 protected void processWindowEvent(WindowEvent e){
   try{
     if (e.getID() == WindowEvent.WINDOW_CLOSING) {
       reader.close();
       socket.close();
     this.setVisible(false);
     this.dispose();
     }
   }catch(Exception se){
     JOptionPane.showMessageDialog(null,"can not disconnect normally");
   }

 }


}

⌨️ 快捷键说明

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