溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java實(shí)現(xiàn)簡(jiǎn)單聊天室單人版

發(fā)布時(shí)間:2020-09-23 23:33:43 來源:腳本之家 閱讀:265 作者:JEROCHAN 欄目:編程語言

本文實(shí)例為大家分享了java實(shí)現(xiàn)簡(jiǎn)單聊天室的具體代碼,供大家參考,具體內(nèi)容如下

先整理下思路:

1.創(chuàng)建一個(gè)通信服務(wù)端,傳入端口號(hào)和相關(guān)的流后等待客戶端連接,并初始化圖形界面。
2.創(chuàng)建一個(gè)JFrame,用于寫出聊天的界面,這里界面名稱由其他類傳入。
3.把客戶端創(chuàng)建的方法寫進(jìn)JFrame(當(dāng)然這里很粗糙的方法)
4.設(shè)置按鈕的監(jiān)聽事件,發(fā)送消息和離線功能

首先創(chuàng)建一個(gè)服務(wù)端的類

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import com.jero.jframe.ChatSocketJFrame;
//創(chuàng)建服務(wù)端
public class ChatServerSocket{
  //構(gòu)造初始化方法
  public ChatServerSocket(String name,int port) throws IOException{
    //創(chuàng)建Socket服務(wù)連接對(duì)象  
      ServerSocket serverSocket = new ServerSocket(port);
    //等待客戶端連接
      Socket client = serverSocket.accept();
    //初始化聊天界面  
      try {
        new ChatSocketJFrame(name,client);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    //關(guān)閉流
      serverSocket.close();
  }
  public static void main(String[] args) throws Exception{
    new ChatServerSocket("服務(wù)端",8001);//啟動(dòng)服務(wù)端,指定網(wǎng)名和端口
  }

}
package com.jero.jframe;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

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

import com.jero.socket.ChatServerSocket;

import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JTextArea;

public class ChatSocketJFrame extends JFrame implements ActionListener {
  private Socket socket;
  private String name;
  private JButton BT_SEND,BT_LEAVE,BT_LOGIN;
  private JTextArea textArea;
  private JPanel contentPane;
  private JTextField textField;
  private PrintWriter cout;
  /**
   * Launch the application.
   * @throws Exception 
   * @throws IOException 
   * @throws UnknownHostException 
   */
  public static void main(String[] args) throws UnknownHostException, IOException, Exception {
    //實(shí)例化界面以及客戶端
    new ChatSocketJFrame("客戶端","127.0.0.1",8001);
  }

  /**
   * Create the frame.
   */
  public ChatSocketJFrame(String name, Socket socket)throws Exception, IOException {
    //聊天室界面
    super("聊天室"+name+" "+InetAddress.getLocalHost()+" "+socket.getPort());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 733, 519);
    this.textArea = new JTextArea();
    this.textArea.setEditable(false);
    this.getContentPane().add(new JScrollPane(this.textArea));
    JPanel panel = new JPanel();
    this.getContentPane().add(panel, "South");
    this.textField = new JTextField(16);
    panel.add(this.textField);
    BT_SEND = new JButton("發(fā)送");
    panel.add(BT_SEND);
    BT_SEND.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        System.out.println("按鈕已點(diǎn)擊");
        cout.println(name+"說: "+textField.getText()+"\n");
        textArea.append("我說: "+textField.getText()+"\n");
        textField.setText("");
      }
    });
    BT_LEAVE = new JButton("離線");
    panel.add(BT_LEAVE);
    BT_LEAVE.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        textArea.append("我離線");
        cout.println(name+"離線\n"+"bye");
        BT_LEAVE.setEnabled(false);
        BT_SEND.setEnabled(false);
      }
    });
    this.setVisible(true);
    //開始創(chuàng)建通信
    this.socket = socket;
    this.name = name;
    //獲得Socket的輸出流并立即刷新
    this.cout = new PrintWriter(socket.getOutputStream(),true);
    //把網(wǎng)名傳給對(duì)方
    this.cout.println(name);
    //獲得Socket對(duì)象的輸入流,創(chuàng)建字符輸入流
    BufferedReader buff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    //接受對(duì)方的網(wǎng)名
    String aline = buff.readLine();
    //顯示對(duì)方發(fā)送的內(nèi)容
    textArea.append("連接"+aline+"成功??!\n");
    aline = buff.readLine();
    //如果內(nèi)容不為空并且對(duì)方不離線,則相互傳送消息
    while(aline!=null&&!aline.equals("bye")){

      textArea.append(aline+"\r\n");
      aline = buff.readLine();
    }
    //當(dāng)對(duì)方離線時(shí),關(guān)閉所有的流
    buff.close();
    cout.close();
    socket.close();
    //把按鈕設(shè)置為不可操作
    BT_SEND.setEnabled(false);
    BT_LEAVE.setEnabled(false);
  }


  /**
   * @wbp.parser.constructor
   */
  public ChatSocketJFrame(String name,String host,int port) throws UnknownHostException, IOException, Exception{
    //創(chuàng)建客戶端
    this(name,new Socket(host,port));
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    //可以把動(dòng)作監(jiān)聽寫進(jìn)此函數(shù),這個(gè)就不演示了
  }
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。 

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI