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

作者:风吹山岗 时间:2022-03-31 17:47:35 

本文实例为大家分享了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);
 }

}

}

来源:https://blog.csdn.net/linzammyy/article/details/51594445

标签:java,聊天室
0
投稿

猜你喜欢

  • Unity实现轮盘方式的按钮滚动效果

    2022-06-19 16:53:57
  • 详解JAVA高质量代码之数组与集合

    2022-03-31 16:42:07
  • OpenCV实现图像背景虚化效果原理详解

    2021-12-06 02:25:59
  • vc提示unexpected end of file found的原因分析

    2022-01-19 12:58:00
  • c#将字节数组转成易读的字符串的实现

    2022-03-02 21:38:31
  • Java爬虫实现Jsoup利用dom方法遍历Document对象

    2023-06-15 07:52:36
  • 使用游长编码对字符串压缩 Run Length编码示例

    2022-02-18 06:58:51
  • 基于C#的图表控件库 ScottPlot编译visual studio 2022

    2022-05-02 10:24:13
  • PC蓝牙通信C#代码实现

    2023-07-06 19:59:32
  • Java实例讲解Comparator的使用

    2021-07-15 09:16:58
  • Java Floyd算法求有权图(非负权)的最短路径并打印

    2023-04-10 12:53:42
  • 详解Spring中的FactoryBean

    2022-06-08 05:29:55
  • java实现动态 代理方法浅析

    2023-11-28 23:33:59
  • Android编程简易实现XML解析的方法详解

    2023-12-25 18:51:59
  • C#实现更改MDI窗体背景颜色的方法

    2021-07-01 13:06:16
  • Ireport的安装与使用教程

    2021-08-08 00:16:43
  • RocketMQ producer容错机制源码解析

    2022-05-14 13:39:41
  • 详解Java中的字节码增强技术

    2022-08-20 06:25:12
  • android使用Path绘制出多边形

    2021-11-11 19:53:38
  • eclipse导入appcompat项目报错解决办法

    2021-11-10 14:25:57
  • asp之家 软件编程 m.aspxhome.com