1. 程式人生 > >java 界面編程用socket實現服務端與客戶端的循環通信。

java 界面編程用socket實現服務端與客戶端的循環通信。

accept star return IE while fde trac AS inf

服務端:

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實現服務端與客戶端的循環通信。