最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java實戰(zhàn)之基于TCP實現簡單聊天程序

 更新時間:2022年03月19日 08:47:04   作者:howard2005  
這篇文章主要為大家詳細介紹了如何在Java中基于TCP實現簡單聊天程序,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

一、如何實現TCP通信

要實現TCP通信需要創(chuàng)建一個服務器端程序和一個客戶端程序,為了保證數據傳輸的安全性,首先需要實現服務器端程序,然后在編寫客戶端程序。

在本機運行服務器端程序,在遠程機運行客戶端程序

本機的IP地址:192.168.129.222

遠程機的IP地址:192.168.214.213

二、編寫C/S架構聊天程序

1.編寫服務器端程序 - Server.java

在net.hw.network包里創(chuàng)建Server類

package net.hw.network;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 功能:服務器端
 * 作者:華衛(wèi)
 * 日期:2022年03月18日
 */
public class Server extends JFrame {
    static final int PORT = 8136;
    static final String HOST_IP = "192.168.129.222";

    private JPanel panel1, panel2;
    private JTextArea txtContent, txtInput, txtInputIP;
    private JScrollPane panContent, panInput;
    private JButton btnClose, btnSend;

    private ServerSocket serverSocket;
    private Socket socket;
    private DataInputStream netIn;
    private DataOutputStream netOut;

    public static void main(String[] args) {
        new Server();
    }

    public Server() {
        super("服務器");

        //創(chuàng)建組件
        panel1 = new JPanel();
        panel2 = new JPanel();
        txtContent = new JTextArea(15, 60);
        txtInput = new JTextArea(3, 60);
        panContent = new JScrollPane(txtContent, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        panInput = new JScrollPane(txtInput, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        btnClose = new JButton("關閉");
        btnSend = new JButton("發(fā)送");

        //添加組件
        getContentPane().add(panContent, "Center");
        getContentPane().add(panel1, "South");
        panel1.setLayout(new GridLayout(0, 1));
        panel1.add(panInput);
        panel1.add(panel2);
        panel2.add(btnSend);
        panel2.add(btnClose);

        //設置組件屬性
        txtContent.setEditable(false);
        txtContent.setFont(new Font("宋體", Font.PLAIN, 13));
        txtInput.setFont(new Font("宋體", Font.PLAIN, 15));
        txtContent.setLineWrap(true);
        txtInput.setLineWrap(true);
        txtInput.requestFocus();
        setSize(450, 350);
        setLocation(50, 200);
        setResizable(false);
        setVisible(true);

        //等候客戶請求	
        try {
            txtContent.append("服務器已啟動...\n");
            serverSocket = new ServerSocket(PORT);
            txtContent.append("等待客戶請求...\n");
            socket = serverSocket.accept();
            txtContent.append("連接一個客戶。\n" + socket + "\n");
            netIn = new DataInputStream(socket.getInputStream());
            netOut = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        /

        //注冊監(jiān)聽器,編寫事件代碼	
        txtContent.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayClientMsg();
            }
        });

        txtInput.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayClientMsg();
            }
        });

        panel2.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayClientMsg();
            }
        });

        txtInput.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                displayClientMsg();
            }
        });

        txtInput.addFocusListener(new FocusAdapter() {
            public void focusGained(FocusEvent e) {
                displayClientMsg();
            }
        });

        btnSend.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {

                    String serverMsg = txtInput.getText();
                    if (!serverMsg.trim().equals("")) {
                        txtContent.append("服務器>" + serverMsg + "\n");
                        netOut.writeUTF(serverMsg);
                    } else {
                        JOptionPane.showMessageDialog(null, "不能發(fā)送空信息!", "服務器", JOptionPane.WARNING_MESSAGE);
                    }

                    txtInput.setText("");
                    txtInput.requestFocus();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
            }
        });

        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    netIn.close();
                    netOut.close();
                    socket.close();
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.exit(0);
            }
        });

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                try {
                    netIn.close();
                    netOut.close();
                    socket.close();
                    serverSocket.close();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
                System.exit(0);
            }

            public void windowActivated(WindowEvent e) {
                txtInput.requestFocus();
            }
        });
    }

    //顯示客戶端信息
    void displayClientMsg() {
        try {
            if (netIn.available() > 0) {
                String clientMsg = netIn.readUTF();
                txtContent.append("客戶端>" + clientMsg + "\n");
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

2.編寫客戶端程序 - Client.java

在net.hw.network包里創(chuàng)建Client類

package net.hw.network;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 功能:客戶端
 * 作者:華衛(wèi)
 * 日期:2022年03月18日
 */
public class Client extends JFrame {

    private JPanel panel1, panel2;
    private JTextArea txtContent, txtInput;
    private JScrollPane panContent, panInput;
    private JButton btnClose, btnSend;

    private Socket socket;
    private DataInputStream netIn;
    private DataOutputStream netOut;

    public static void main(String[] args) {
        new Client();
    }

    public Client() {
        super("客戶端");

        //創(chuàng)建組件
        panel1 = new JPanel();
        panel2 = new JPanel();
        txtContent = new JTextArea(15, 60);
        txtInput = new JTextArea(3, 60);
        panContent = new JScrollPane(txtContent, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        panInput = new JScrollPane(txtInput, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        btnClose = new JButton("關閉");
        btnSend = new JButton("發(fā)送");

        //添加組件
        getContentPane().add(panContent, "Center");
        getContentPane().add(panel1, "South");
        panel1.setLayout(new GridLayout(0, 1));
        panel1.add(panInput);
        panel1.add(panel2);
        panel2.add(btnSend);
        panel2.add(btnClose);

        //設置組件屬性
        txtContent.setEditable(false);
        txtContent.setFont(new Font("宋體", Font.PLAIN, 13));
        txtInput.setFont(new Font("宋體", Font.PLAIN, 15));
        txtContent.setLineWrap(true);
        txtInput.setLineWrap(true);
        txtInput.requestFocus();
        setSize(450, 350);
        setLocation(550, 200);
        setResizable(false);
        setVisible(true);

        //連接服務器
        try {
            txtContent.append("連接服務器...\n");
            socket = new Socket(Server.HOST_IP, Server.PORT);
            txtContent.append("連接服務器成功。\n" + socket + "\n");
            netIn = new DataInputStream(socket.getInputStream());
            netOut = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e1) {
            JOptionPane.showMessageDialog(null, "服務器連接失?。n請先啟動服務器程序!", "客戶端", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

        /

        //注冊監(jiān)聽器,編寫事件代碼
        txtContent.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayServerMsg();
            }
        });

        txtInput.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayServerMsg();
            }
        });

        panel2.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayServerMsg();
            }
        });

        txtInput.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                displayServerMsg();
            }
        });

        txtInput.addFocusListener(new FocusAdapter() {
            public void focusGained(FocusEvent e) {
                displayServerMsg();
            }
        });

        btnSend.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {

                    String clientMsg = txtInput.getText();
                    if (!clientMsg.trim().equals("")) {
                        netOut.writeUTF(clientMsg);
                        txtContent.append("客戶端>" + clientMsg + "\n");
                    } else {
                        JOptionPane.showMessageDialog(null, "不能發(fā)送空信息!", "客戶端", JOptionPane.WARNING_MESSAGE);
                    }

                    txtInput.setText("");
                    txtInput.requestFocus();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
            }
        });

        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    netIn.close();
                    netOut.close();
                    socket.close();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
                System.exit(0);
            }
        });

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                try {
                    netIn.close();
                    netOut.close();
                    socket.close();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
                System.exit(0);
            }

            public void windowActivated(WindowEvent e) {
                txtInput.requestFocus();
            }
        });
    }

    //顯示服務端信息
    void displayServerMsg() {
        try {
            if (netIn.available() > 0) {
                String serverMsg = netIn.readUTF();
                txtContent.append("服務器>" + serverMsg + "\n");
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

3.測試服務器端與客戶端能否通信

在本機[192.168.129.222]上啟動服務器端

在遠程機[192.168.214.213]上啟動客戶端

顯示連接服務器[192.168.129.222]成功,切換到服務器端查看,顯示連接了一個客戶[192.168.214.213]

此時,服務器端和客戶端就可以相互通信了

4.程序優(yōu)化思路 - 服務器端采用多線程

其實,很多服務器端程序都是允許被多個應用程序訪問的,例如門戶網站可以被多個用戶同時訪問,因此服務器端都是多線程的。

以上就是Java實戰(zhàn)之基于TCP實現簡單聊天程序的詳細內容,更多關于Java TCP聊天程序的資料請關注腳本之家其它相關文章!

相關文章

  • java?String到底有多長?String超出長度該如何解決

    java?String到底有多長?String超出長度該如何解決

    在Java中,由于字符串常量池的存在,String常量長度限制取決于String常量在常量池中的存儲大小,下面這篇文章主要給大家介紹了關于java?String到底有多長?String超出長度該如何解決的相關資料,需要的朋友可以參考下
    2023-01-01
  • 基于Java8并行流(parallelStream)的注意點

    基于Java8并行流(parallelStream)的注意點

    這篇文章主要介紹了Java8并行流(parallelStream)的注意點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • springboot上傳zip包并解壓至服務器nginx目錄方式

    springboot上傳zip包并解壓至服務器nginx目錄方式

    這篇文章主要介紹了springboot上傳zip包并解壓至服務器nginx目錄方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-04-04
  • java解析json數組方式

    java解析json數組方式

    這篇文章主要介紹了java解析json數組方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • SpringBoot集成阿里巴巴Druid監(jiān)控的示例代碼

    SpringBoot集成阿里巴巴Druid監(jiān)控的示例代碼

    這篇文章主要介紹了SpringBoot集成阿里巴巴Druid監(jiān)控的示例代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • SpringAOP中的Advisor詳解

    SpringAOP中的Advisor詳解

    這篇文章主要介紹了SpringAOP中的Advisor詳解,平時我們項目中涉及到?AOP,基本上就是聲明式配置一下就行了,無論是基于?XML?的配置還是基于?Java?代碼的配置,都是簡單配置即可使用,今天就來看一下聲明式配置的使用,需要的朋友可以參考下
    2023-08-08
  • Java延時的3種實現方法舉例

    Java延時的3種實現方法舉例

    這篇文章主要給大家介紹了關于Java延時的3種實現方法舉例,java開發(fā)中常會用到延時任務,文中通過實例代碼介紹的非常詳細,對大家的學習具有一定參考借鑒價值,需要的朋友可以參考下
    2023-07-07
  • Spring?Cloud灰度部署實現過程詳解

    Spring?Cloud灰度部署實現過程詳解

    這篇文章主要為大家介紹了Spring?Cloud灰度部署實現過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-06-06
  • Spring MVC中自定義攔截器的實例講解

    Spring MVC中自定義攔截器的實例講解

    下面小編就為大家?guī)硪黄猄pring MVC中自定義攔截器的實例講解。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • Java遞歸來實現漢諾塔游戲,注釋詳細

    Java遞歸來實現漢諾塔游戲,注釋詳細

    這篇文章介紹了Java遞歸來實現漢諾塔游戲的方法,文中的代碼注釋介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-11-11

最新評論

吐鲁番市| 马尔康县| 扎赉特旗| 改则县| 阿克陶县| 阳朔县| 邵武市| 洪雅县| 巫溪县| 嘉兴市| 九龙城区| 伊吾县| 枝江市| 铜川市| 遂溪县| 邵武市| 巴中市| 乌拉特中旗| 邵武市| 饶平县| 南木林县| 霍林郭勒市| 新竹县| 常州市| 高清| 十堰市| 社会| 治县。| 太谷县| 赣州市| 松滋市| 绍兴市| 绥滨县| 阜南县| 锦州市| 湖口县| 开平市| 汝南县| 孟津县| 渭源县| 祥云县|