Java中利用Tcp/ip連接多人交互聊天室的實現(xiàn)-創(chuàng)新互聯(lián)

Java中利用Tcp/ip連接多人交互聊天室的實現(xiàn),針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

堅守“ 做人真誠 · 做事靠譜 · 口碑至上 · 高效敬業(yè) ”的價值觀,專業(yè)網站建設服務10余年為成都玻璃貼膜小微創(chuàng)業(yè)公司專業(yè)提供企業(yè)網站制作營銷網站建設商城網站建設手機網站建設小程序網站建設網站改版,從內容策劃、視覺設計、底層架構、網頁布局、功能開發(fā)迭代于一體的高端網站建設服務。

使用指南:

1.運行Server.java文件,保證服務端的開啟
2.運行UI.java文件,界面登陸。每運行一個UI文件并登陸進去,就代表一個客戶進了群聊中,可進行對話。

程序簡單易懂,非常適合初學者練習網絡編程的知識。

Client.java

import java.net.*;
import java.io.*;
import java.util.*;

public class Client{

  String name;
  Socket s;
  UI ui;
  //構造方法 ,把UI對象傳過來
  public Client(UI ui){
    this.ui = ui;
  }

  //從登陸界面獲得名字并傳去服務端
  public void getName(String name){
    try{
    s = new Socket("127.0.0.1",3000);
    Cli1 d = new Cli1(s,ui);
    d.start();
    this.name = name;
    DataOutputStream dos = new DataOutputStream(s.getOutputStream());
    dos.writeUTF(name);
    }catch(Exception e){
      e.printStackTrace();
    }
  }
  //從聊天界面獲得要發(fā)送的內容并經服務器轉發(fā)給各個客戶端
  public void say(String content){
    try{
    DataOutputStream dos = new DataOutputStream(s.getOutputStream());
    dos.writeUTF(content);
    }catch(Exception e){
      e.printStackTrace();
    }
  }

}

//輸入和輸出
class Cli1 extends Thread {
  UI ui;
  Socket s ;
  public Cli1(Socket s,UI ui){
    this.s = s;
    this.ui=ui;
  }
  public void run(){
    try{
    while(true){

      DataInputStream dis = new DataInputStream(s.getInputStream());
      String content = dis.readUTF();
      if(!content.equals("")&&content!=null){
        System.out.println(content);
        ui.say(content);
      }

    }
    }catch(Exception e){
      e.printStackTrace();
    }
  }
}

Server.java

import java.net.*;
import java.io.*;
import java.util.*;

public class Server{
  static Socket s;
  static Socket[] soc;
  static String[] name;
  static int k = 5,i =0,j;
  public static void main(String[] args){

    Server ser = new Server();
    try{
      ServerSocket ss = new ServerSocket(3000);


      soc = new Socket[k]; 
      name = new String[k];
      while(true){
        s = ss.accept();
        soc[i]= s;
        j=i;
        i++;
        DataOutputStream dos = new DataOutputStream(s.getOutputStream()); 

        DataInputStream dis = new DataInputStream(s.getInputStream());
        name[j] = dis.readUTF();
        System.out.println(name[j]+"已進入群聊!");
        dos.writeUTF("歡迎你,"+name[j]);
        new Ser1().start();

      }
    }catch(ConnectException e){
      System.out.println("連接異常!!");

    }catch(IOException e){
      e.printStackTrace();
    }

  }


}

class Ser1 extends Thread{

  public int j;

  public void run(){
    try{
    DataInputStream read = new DataInputStream((Server.soc[Server.j]).getInputStream());
    j=Server.j;
    while(true){
      String con = read.readUTF();

      if(con!=null){


        System.out.println("該線程j為"+j);
        for(int i = 0;i<Server.soc.length;i++){
          if((i!=j)&&(Server.soc[i]!=null)){
            DataOutputStream dos = new DataOutputStream((Server.soc[i]).getOutputStream()); 
            dos.writeUTF(Server.name[Server.j]+"發(fā)送于 "+(new Date()));
            dos.writeUTF(con);
          }
        }


      }else{break;}
    }

  }catch(Exception e){
    e.printStackTrace();
  }
  }

}

UI.java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class UI{

  //主方法
  public static void main(String[] args){

    UI ui = new UI();
    ui.cli = new Client(ui);
    ui.initFrame();
    ui.showLogin();
  }

  Ser1 ser1 = new Ser1();

  //初始化業(yè)務對象
  public Client cli = null;
  public void initCli(){

  }

  //初始化主窗口
  public int width = 720;
  public int height = 550;
  public JFrame jFrame = null; //界面窗口
  public JLayeredPane layeredPane = null; //層疊容器
  public JPanel backLayer = null; //背景層
  public JPanel frontLayer = null; //前景層
  public CardLayout cardLayout = null; //前景層布局器

  public void initFrame(){
    jFrame = new JFrame("老友聚樂部");
    layeredPane = new JLayeredPane();
    layeredPane.setPreferredSize(new Dimension(width, height));
    jFrame.add(layeredPane);
    jFrame.setResizable(false);
    jFrame.pack();
     jFrame.setVisible(true);
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    backLayer = new JPanel();
    ((FlowLayout)backLayer.getLayout()).setHgap(0);
    ((FlowLayout)backLayer.getLayout()).setVgap(0);
    backLayer.setSize(width,height);
    backLayer.setLocation(0,0);
    JLabel bg = new JLabel(new ImageIcon("12.jpg"));
    backLayer.add(bg);


    layeredPane.add(backLayer,new Integer(0));

    frontLayer = new JPanel();
    cardLayout = new CardLayout(0,0);
    frontLayer.setLayout(cardLayout);
    frontLayer.setOpaque(false);
    frontLayer.setSize(width,height);
    frontLayer.setLocation(0,0);

    layeredPane.add(frontLayer,new Integer(1));

  }

  //登錄界面
  public JPanel loginPane = null;
  public JTextField loginCodeInput = null;

  public JLabel loginTipsLabel = null;
  public void showLogin(){
    if(loginPane == null){
      loginPane = new JPanel();
      loginPane.setOpaque(false);

      Box loginBox = Box.createVerticalBox();
      loginBox.add(Box.createVerticalStrut(180));

      JPanel welcome_panel = new JPanel();
      welcome_panel.setOpaque(false);
      JLabel welcome_label = new JLabel("老友俱樂部");

      welcome_label.setForeground(Color.WHITE);
      welcome_label.setFont(new Font("微軟雅黑",Font.PLAIN,30));
      welcome_panel.add(welcome_label);
      loginBox.add(welcome_panel);

      loginBox.add(Box.createVerticalStrut(50));
      JPanel code_panel = new JPanel();
      code_panel.setOpaque(false);
      JLabel code_label = new JLabel("姓名:");
      code_label.setForeground(Color.WHITE);
      code_label.setFont(new Font("微軟雅黑",Font.PLAIN,25));
      code_panel.add(code_label);
      loginCodeInput = new JTextField(10);
      loginCodeInput.setFont(new Font("微軟雅黑", Font.PLAIN,25));
      code_panel.add(loginCodeInput);
      loginBox.add(code_panel);

      loginBox.add(Box.createVerticalStrut(30));

      JPanel btn_panel = new JPanel();
      btn_panel.setOpaque(false);
      JButton login_btn = new JButton("登 錄");
      login_btn.setFont(new Font("微軟雅黑",Font.PLAIN,15));
      btn_panel.add(login_btn);

      JButton reset_btn = new JButton("重 置");
      reset_btn.setFont(new Font("微軟雅黑",Font.PLAIN,15));
      btn_panel.add(reset_btn);
      loginBox.add(btn_panel);

      loginBox.add(Box.createVerticalStrut(10));

      JPanel tips_panel = new JPanel();
      tips_panel.setOpaque(false);
      loginTipsLabel = new JLabel("");
      loginTipsLabel.setForeground(new Color(238,32,32));
      loginTipsLabel.setFont(new Font("微軟雅黑",Font.PLAIN,20));
      tips_panel.add(loginTipsLabel);
      loginBox.add(tips_panel);

      loginPane.add(loginBox);

      frontLayer.add("loginPane",loginPane);
      cardLayout.show(frontLayer,"loginPane");
      frontLayer.validate();
      loginCodeInput.requestFocus();

      reset_btn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
          loginCodeInput.setText("");
          loginTipsLabel.setText("");
          loginCodeInput.requestFocus();
        }
      });

      login_btn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
          String code_str = loginCodeInput.getText();

          if("".equals(code_str)){
            loginTipsLabel.setText("姓名不能為空!");
            loginCodeInput.requestFocus();

          }else{

            cli.getName(code_str);

            showTalk();

          }
        }
      });
    }else{
      cardLayout.show(frontLayer,"loginPane");
      loginCodeInput.setText("");

      loginTipsLabel.setText("");
      loginCodeInput.requestFocus();
    }
  }

  //聊天主界面
  public JPanel menuPane = null;
  public JTextArea input = null;
  public JTextArea talk = new JTextArea(25,70);
  public void showTalk(){

      menuPane = new JPanel();
      menuPane.setOpaque(false);
      menuPane.setLayout(new BorderLayout());

      JPanel up = new JPanel();
      Box tipsBox = Box.createVerticalBox();
      menuPane.add(up,BorderLayout.NORTH); //北邊頂上
      up.add(tipsBox);

      JLabel tips_label = new JLabel("在線朋友");
      tips_label.setForeground(Color.WHITE);
      tips_label.setFont(new Font("微軟雅黑",Font.PLAIN,20));
      tips_label.setAlignmentX(Component.LEFT_ALIGNMENT);
      tipsBox.add(tips_label);
      tipsBox.add(Box.createVerticalStrut(10));
      JLabel upTxt = new JLabel(""); //接收在線朋友(需完善)

      tipsBox.add(upTxt);

      JPanel talk_panel = new JPanel();//中間聊天對話框
      talk_panel.setOpaque(false);

      menuPane.add(talk_panel,BorderLayout.WEST);

      JScrollPane sp = new JScrollPane(talk);
      talk_panel.add(talk);

      Box inputBox = Box.createHorizontalBox(); //下邊輸入框
      menuPane.add(inputBox,BorderLayout.SOUTH);

      JPanel input_panel = new JPanel();
      input_panel.setOpaque(false); //放置輸入框
      input = new JTextArea(4,30);
      input.setFont(new Font("微軟雅黑",Font.PLAIN,20));
      input.setAlignmentX(Component.LEFT_ALIGNMENT);
      input_panel.add(input);
      inputBox.add(input_panel);
      inputBox.add(Box.createHorizontalStrut(0));
      JButton send_btn = new JButton("發(fā)送");
      send_btn.setFont(new Font("微軟雅黑",Font.PLAIN,15));
      inputBox.add(send_btn);

      frontLayer.add("menuPane",menuPane);
      cardLayout.show(frontLayer,"menuPane");
      frontLayer.validate();

      send_btn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
          String append = talk.getText();
          String content = input.getText();
          talk.setText(append+'\n'+content);
          input.setText("");
          cli.say(content);

        }
      });


  }
  public void say(String content){
    if(talk!=null){
      String append = talk.getText();

      talk.setText(append+'\n'+content);
    }

  } 

}

關于Java中利用Tcp/ip連接多人交互聊天室的實現(xiàn)問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關知識。

文章題目:Java中利用Tcp/ip連接多人交互聊天室的實現(xiàn)-創(chuàng)新互聯(lián)
分享URL:http://muchs.cn/article48/ejeep.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、企業(yè)建站、網站設計公司、服務器托管網站策劃、靜態(tài)網站

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司