欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java基于Tcp/ip连接的多人交互聊天室

程序员文章站 2024-02-15 20:25:52
本文实例为大家分享了java  socket编程实现多人交互聊天室的具体代码,供大家参考,具体内容如下 本项目由三个.java文件(client.java、se...

本文实例为大家分享了java  socket编程实现多人交互聊天室的具体代码,供大家参考,具体内容如下

本项目由三个.java文件(client.java、server.java、ui.java)和一个.jpg图片文件组成ui.java是负责界面的构成文件。本聊天室的界面极其简单。主要分为两个界面:第一个是启动时需要登陆的界面如下:

Java基于Tcp/ip连接的多人交互聊天室 

输入名字进去以后就可以直接聊天

Java基于Tcp/ip连接的多人交互聊天室 
Java基于Tcp/ip连接的多人交互聊天室 
Java基于Tcp/ip连接的多人交互聊天室

这个聊天室相当于群聊,每一个登陆进去的人发的信息,其他人都会收到。
使用指南:

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();
    }
  }
  //从聊天界面获得要发送的内容并经服务器转发给各个客户端
  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]+"发送于 "+(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();

  //初始化业务对象
  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("发送");
      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);
    }

  } 

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。