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
投稿

猜你喜欢

  • java跟踪执行的sql语句示例分享

    2022-07-30 20:13:18
  • Java基础:流Stream详解

    2023-11-29 06:11:14
  • C# 文字代码页 文字编码的代码页名称速查表

    2023-12-13 04:03:54
  • Spring JDBC的使用方法详解

    2021-12-08 14:05:42
  • SpringBoot应用War包形式部署到外部Tomcat的方法

    2021-10-06 04:59:48
  • HashMap工作原理_动力节点Java学院整理

    2023-06-20 20:33:15
  • Java深入了解数据结构之二叉搜索树增 插 删 创详解

    2023-02-14 08:08:00
  • Java几种常用的断言风格你怎么选

    2021-10-30 23:30:32
  • 浅谈java中String StringBuffer StringBuilder的区别

    2023-11-29 13:34:40
  • JAVA集合框架Map特性及实例解析

    2021-06-05 02:23:39
  • SpringBoot下使用MyBatis-Puls代码生成器的方法

    2023-11-25 17:07:07
  • Java雇员管理小项目

    2023-02-12 00:39:01
  • 一篇文章教你如何用多种迭代写法实现二叉树遍历

    2023-12-23 04:03:29
  • 解决springmvc关于前台日期作为实体类对象参数类型转换错误的问题

    2023-11-28 20:53:42
  • 基于Unity制作一个简易的计算器

    2023-02-18 10:02:39
  • java获取百度网盘真实下载链接的方法

    2021-09-07 21:16:08
  • Java中包装类介绍与其注意事项

    2023-03-20 18:26:36
  • 使用JAVA实现http通信详解

    2023-11-12 12:21:12
  • java spring mvc处理器映射器介绍

    2021-11-22 01:01:35
  • 关于SpringCloud的微服务结构及微服务远程调用

    2021-11-06 20:11:45
  • asp之家 软件编程 m.aspxhome.com