listeningserver.java~1~

来自「一个简单的聊天程序」· JAVA~1~ 代码 · 共 65 行

JAVA~1~
65
字号
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,20);
 JTextField input=new JTextField(20);
 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);
    input.addActionListener(this);
    try{
    reader=new DataInputStream(socket.getInputStream());
    writer=new PrintStream(socket.getOutputStream());
    }catch(Exception e){
      JOptionPane.showMessageDialog(null,"IO error");
    }
    this.setBounds(200,200,200,200);
    this.setVisible(true);


  }
  public void run(){

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

      }
    }catch(Exception e){
      JOptionPane.showMessageDialog(null,"can not read from client");
    }
  }

  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);
    temp.append(area.getText());
    area.setText(temp.toString());

 }



}

⌨️ 快捷键说明

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