java 界面编程用socket实现服务端与客户端的循环通信。

时间:2023-01-24 22:15:48

服务端:

package 实验五聊天;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;


import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class 服务端 extends JFrame implements  Runnable {

    private JPanel contentPane;
    private JTextField textField;
    private  static JTextArea BtextArea;
    public static ServerSocket serverSocket=null;
    public static Socket clientSocket=null;
    //public static PrintWriter out=null;
    public static DataOutputStream out=null;
    public static DataInputStream in=null;
        public void run()//接收信息
        {
            try
            {
                while(true)
                {
                    if(in!=null)
                        {
                            String tmp=in.readUTF();
                            BtextArea.append("\n客户端:\n"+tmp);
                        }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }    
        }
    private Thread thread;
    public void connect()
    {
        try
        {
            serverSocket =new ServerSocket(8000);
            clientSocket=serverSocket.accept();
            in=new DataInputStream(clientSocket.getInputStream());
            out=new DataOutputStream(clientSocket.getOutputStream());
            System.out.println("链接成功");
            if (!(thread.isAlive())) { 
                thread = new Thread(this);
            }
            thread.start();
        }
        catch(Exception e)
        {
            System.out.println("连接失败");
            e.printStackTrace();
        }
        
    }
    public void send()
    {
        try
        {
            String tmp=textField.getText();
            textField.setText("");
            if(tmp.isEmpty())
            {
                JOptionPane.showMessageDialog(this, "请输入信息");
                return;
            }
            BtextArea.append("\n服务端:\n"+tmp);
                 if(out!=null)
                     {
                         out.writeUTF(tmp);
                     }
                 else
                 {
                     System.out.println("链接未建立");
                 }
        }
        catch(Exception e1)
        {
            e1.printStackTrace();
        }
    }
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    服务端 frame = new 服务端();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public 服务端() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("服务端");
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        JTextArea textArea = new JTextArea();
        BtextArea =textArea;
        textArea.setBounds(0, 15, 300, 137);
        //contentPane.add(textArea);
        JScrollPane jsp = new JScrollPane(textArea); //在文本框上添加滚动条
        jsp.setBounds(0, 15, 350, 100);
        //默认的设置是超过文本框才会显示滚动条,以下设置让滚动条一直显示
         jsp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         
        contentPane.add(jsp);
        textField = new JTextField();
        textField.setBounds(0, 167, 287, 62);
        contentPane.add(textField);
        textField.setColumns(10);
        
        JButton button = new JButton("\u53D1\u9001");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                send();
            }
            });
        button.setBounds(302, 200, 123, 29);
        contentPane.add(button);
        
        JButton button_1 = new JButton("\u5F00\u59CB\u670D\u52A1");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                connect();        
            }
        });
        button_1.setBounds(302, 147, 123, 29);
        contentPane.add(button_1);
        thread=new Thread(this);
        //thread.run();
    }
}

 

客户端:

package 实验五聊天;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;

import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class 客户端 extends JFrame implements  Runnable{

    private JPanel contentPane;
    private JTextField textField;
    private JButton button;
    private  static JTextArea BtextArea;
    public static ServerSocket serverSocket=null;
    public static Socket clientSocket=null;
    public  Socket client=null;
    public DataOutputStream out=null;
    public static DataInputStream in=null;
    private Thread thread;
    public void run()
        {
            try
            {
                while(true)
                {        
                    
                    if(in!=null)
                        {
                            String tmp=in.readUTF();
                            BtextArea.append("\n服务端:\n"+tmp);
                        }
                }
            
            }catch (Exception e) {
                e.printStackTrace();
            }    
        }
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    客户端 frame = new 客户端();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    //frame.setTitle("客户端");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public void  connect()
    {
            InetAddress localIP=null;
            try {
                if(client==null)
                {
                    localIP = InetAddress.getLocalHost();
                    client=new Socket(localIP,8000);
                    out=new DataOutputStream(client.getOutputStream());
                    in=new DataInputStream(client.getInputStream());
                    if(!(thread.isAlive()))
                    {
                        thread=new Thread(this);
                    }
                    thread.start();
                }
            } catch (UnknownHostException   e2) {
                // TODO 自动生成的 catch 块
                e2.printStackTrace();
            }
            catch(IOException e2)
            {
                e2.printStackTrace();
            }
    }
    /**
     * Create the frame.
     */
    public 客户端() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        setTitle("客户端");
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        JTextArea textArea = new JTextArea();
        textArea.setBounds(0, 0, 299, 132);
        BtextArea=textArea;
        JScrollPane jsp = new JScrollPane(textArea); //在文本框上添加滚动条
        jsp.setBounds(0, 15, 350, 100);
        //默认的设置是超过文本框才会显示滚动条,以下设置让滚动条一直显示
         jsp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         
        contentPane.add(jsp);
        
        textField = new JTextField();
        textField.setBounds(10, 127, 257, 102);
        contentPane.add(textField);
        textField.setColumns(10);
        
        button = new JButton("\u53D1\u9001");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                 String tmp=textField.getText();
                 textField.setText("");
                 BtextArea.append("\n客户端:"+tmp);
                 try
                 {
                     out.writeUTF(tmp);
                 }
                 catch(Exception e1)
                 {
                     e1.printStackTrace();
                 }
            }
        });
        button.setBounds(282, 185, 123, 29);
        contentPane.add(button);
        
        JButton button_1 = new JButton("\u8FDE\u63A5");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                connect();
            }
        });
        button_1.setBounds(282, 130, 123, 29);
        contentPane.add(button_1);
        thread=new Thread(this);
    }
}

实现效果:

java 界面编程用socket实现服务端与客户端的循环通信。

java 界面编程用socket实现服务端与客户端的循环通信。