Java基于Tcp/ip连接的多人交互聊天室
作者:风吹山岗
这篇文章主要为大家详细介绍了Java基于Tcp/ip连接的多人交互聊天室,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Java Socket编程实现多人交互聊天室的具体代码,供大家参考,具体内容如下
本项目由三个.java文件(Client.java、Server.java、UI.java)和一个.jpg图片文件组成UI.java是负责界面的构成文件。本聊天室的界面极其简单。主要分为两个界面:第一个是启动时需要登陆的界面如下:
输入名字进去以后就可以直接聊天
这个聊天室相当于群聊,每一个登陆进去的人发的信息,其他人都会收到。
使用指南:
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); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。