Java源代码___聊天室

合集下载

JAVA局域网聊天系统源代码

JAVA局域网聊天系统源代码

这是我自己做的简单聊天系统客户端package LiaoTianSys;import java.awt.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import .Socket;import .UnknownHostException;public class ConversationFrame extends JFrame {JScrollPane jsp;JTextField jtf;static JTextArea jta;//JTextArea jat1,jta2;JButton enter=new JButton("发送");JButton jb=new JButton("聊天室好友");JButton jb2=new JButton("进入聊天室");JButton jb3=new JButton("刷新在线人员列表");JPanel jp,jp1,jp3,jp4;DefaultListModel listmodel = new DefaultListModel();//static String[] NAME=new String[10];String n[]={"f"};JList list=new JList(listmodel);JLabel time=new JLabel("当前系统时间:");JLabel showtime=new JLabel("显示时间");JLabel jl=new JLabel("输聊天信息");JLabel nicheng=new JLabel("昵称");JTextField NCshuru=new JTextField(10);static DataOutputStream dos;static DataInputStream dis;//final LoginFrame lf;Socket socket;public ConversationFrame(){Container con=getContentPane();con.setLayout(new BorderLayout());jp=new JPanel();setSize(700,600);setLocation(100,100);jta=new JTextArea();jta.setEditable(false);jsp=new JScrollPane(jta);con.add(jsp,BorderLayout.CENTER);jtf=new JTextField(20);jp.add(jl);jp.add(jtf);jp.add(enter);con.add(jp,BorderLayout.SOUTH);jp1=new JPanel(new BorderLayout());JScrollPane jsp1=new JScrollPane(list);jp1.add(jsp1,BorderLayout.CENTER);jp1.add(jb,BorderLayout.NORTH);con.add(jp1,BorderLayout.EAST);//pack();jp3=new JPanel();jp3.add(nicheng);jp3.add(NCshuru);jp3.add(jb2);con.add(jp3,BorderLayout.NORTH);jp4=new JPanel(new GridLayout(10,1));jp4.add(jb3);jp4.add(time);jp4.add(showtime);new getTime(this).start();con.add(jp4,BorderLayout.WEST);setVisible(true);// 发送信息给所有人enter.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) {// TODO Auto-generated method stubString info=jtf.getText();try {dos.writeUTF(NCshuru.getText()+" 对所有人说:"+info);dos.flush();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});//进入聊天室时将自己的昵称发给服务器,首先去验证是否会与已有的人同名,本聊天室是不支持同昵称聊天jb2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){String msg=NCshuru.getText().toString();//得到昵称if(msg.length()==0){JOptionPane.showMessageDialog(null, "昵称不应该为空,", "温馨提示", RMA TION_MESSAGE);}{try{dos.writeUTF("name"+msg);dos.flush();}catch(Exception ex){System.out.println(ex.getMessage());}}}});//向服务器请求更新在线人员列表jb3.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){try {listmodel.removeAllElements();//请求之前删除JList对象中的所有内容dos.writeUTF("请求更新在线人员列表");dos.flush();} catch (IOException e1) {// TODO Auto-generated catch block//e1.printStackTrace();System.out.println(e1.getMessage());}}});//当有在线人员时,双击JList列表某项弹出私聊对话框事件,匿名内部类实现的list.addMouseListener(new MouseAdapter(){public void mouseClicked(MouseEvent e){if(e.getClickCount()==2){int index=list.locationToIndex(e.getPoint());// 获得list表中的索引值String recevier=(String)listmodel.getElementAt(index);//得到索引对应的值String sender=NCshuru.getText();new Danliao(sender,recevier,socket);}}});}public static void main(String[] args) {ConversationFrame Con=new ConversationFrame();Con.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Con.kaishi();}public void kaishi(){try {socket=new Socket("172.16.14.60",8888);dos=new DataOutputStream(socket.getOutputStream());dis=new DataInputStream(socket.getInputStream());pc pc1=new pc(socket,this);//传送套接字,本类对象给pc线程pc1.start();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}// pc线程类,负责接收服务器发送来的信息class pc extends Thread{ ConversationFrame conver;Socket socket;public pc(Socket socket,ConversationFrame conver){this.conver=conver;this.socket=socket;}public void run(){try {int i=0;while(true){String line;//从线路读取信息line=ConversationFrame.dis.readUTF();// 将所有的在线人员昵称发送给JList,并添加到在线人列表中if(line.startsWith("N"))// 服务器发送过来的信息的格式是N+{String na=line.substring(1);try{conver.listmodel.addElement(na);System.out.println(na);}catch(Exception e){System.out.println(e.getMessage());}}//接受服务器发来的广播聊天信息else{ConversationFrame.jta.append(line+"\n");}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println(e.getMessage());}}}服务器端package LiaoTianSys;import java.io.*;import .*;import java.util.*;public class Server implements Runnable{public static final int port=8888;protected ServerSocket ss;static Vector connections;Thread connect;public Server(){try {ss=new ServerSocket(port);connections=new Vector(1000);connect=new Thread(this);connect.start();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args) {new Server();}public void run(){try{while(true){Socket client=ss.accept();System.out.println("客户端连接上");firstthread f=new firstthread(this,client);f.setPriority(Thread.MIN_PRIORITY);f.start();connections.addElement(f);}}catch(IOException e){System.out.println(e.getMessage());}}//向所有人发送聊天信息public void SenAll(String msg){int i;firstthread ft;for(i=0;i<connections.size();i++){ft=(firstthread)connections.elementAt(i);try{ft.out.writeUTF(msg);}catch(Exception e){System.out.println(e.getMessage());}}}//发送单聊信息的方法public void SenOne(String msg){int i;firstthread ft;/*String s1,s2,s3;s1=new String("people");s2=new String(msg.substring(2));//私信为两个字s3=s1.conString msg="我悄悄的对小花说你好啊";cat(s2);*/int begin=msg.indexOf("对");int end=msg.indexOf("说");begin=begin+1;String strNew=msg.substring(begin,end);for(i=0;i<connections.size();i++)//遍历线程,找到要发送的对象{ft=(firstthread)connections.elementAt(i);//遍历线程if(strNew.startsWith()){System.out.println();try{String MSG=msg.substring(7);ft.out.writeUTF(MSG);}catch(IOException e){System.out.println(e.getMessage());}}}}}class firstthread extends Thread{protected Socket client;String line,name=null;DataOutputStream firstout,out;DataInputStream in;Server server;public firstthread(Server server,Socket socket){this.server=server;this.client=socket;try{in=new DataInputStream(client.getInputStream());out=new DataOutputStream(client.getOutputStream());firstout=new DataOutputStream(client.getOutputStream());}catch(IOException e){server.connections.removeElement(this);}}//客户线程运行的方法,不断监听客户线路发送的来的信息,然后决定转发方式public void run(){try{while(true){line=in.readUTF();if(line.startsWith("name")){//获取当前线程firstthreadd=(firstthread)(server.connections.elementAt(server.connections.indexOf(this)));line=line.substring(4);if(==null){=line;}}//将服务器的所有在线人员的昵称发送给所有的客户端else if(line.startsWith("请求更新在线人员列表")){try{for(int i=0;i<server.connections.size();i++){firstthread c=(firstthread)(server.connections.elementAt(i));if(!=null){firstout.writeUTF("N"+);//发送昵称}}}catch(Exception e){System.out.println(e.getMessage());}}else if(line.startsWith("private")){server.SenOne(line);}//发送聊天信息给所有的pc客户端else{server.SenAll(line);}}}catch(IOException e){System.out.println(e.getMessage());}}}显示时间package LiaoTianSys;import java.text.SimpleDateFormat;import java.util.Date;public class getTime extends Thread{String time;ConversationFrame conver;public getTime(ConversationFrame conver){this.conver=conver;System.out.println("获得系统时间");}public void run(){while(true){SimpleDateFormat df=new SimpleDateFormat("HH:mm:ss");time= df.format(new Date());//System.out.println(time);conver.showtime.setText(time);try{this.sleep(1000);}catch(Exception e){System.out.println(e.getMessage());}}}public static void main(String []args){}}单聊package LiaoTianSys;import java.io.DataOutputStream;import java.io.IOException;import .*;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Danliao extends JFrame implements ActionListener{ JButton jb=new JButton("发送");JPanel jp1=new JPanel();JLabel jl=new JLabel("输入聊天信息");JTextField jtf=new JTextField(20);JTextArea jta=new JTextArea();JScrollPane jsp=new JScrollPane(jta);String recevier;String sender;Socket socket;public Danliao(String sender,String recevier,Socket socket) { this.recevier=recevier;this.sender=sender;this.socket=socket;setBackground(Color.red);setTitle("与"+recevier+"单聊");setSize(400,400);setLocation(200,200);Container con=getContentPane();con.setLayout(new BorderLayout());con.add(jsp,BorderLayout.CENTER);jp1.add(jl);jp1.add(jtf);jp1.add(jb);/*addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){//System.exit(0);//this.dispose();//this.hide();this.setVisible(false);}});*/addWindowListener(new Close(this));con.add(jp1,BorderLayout.SOUTH);jb.addActionListener(this);setVisible(true);}public void actionPerformed(ActionEvent e){ String msg=jtf.getText();jta.append(msg+"\n"+"\n");jtf.setText(null);try{DataOutputStream dos=new DataOutputStream(socket.getOutputStream());dos.writeUTF("private"+sender+"悄悄的对"+recevier+"说: "+msg);jtf.setText(null);}catch(Exception e1){e1.printStackTrace();}}public static void main(String[] args){}}//单击关闭窗口事件,隐藏单聊窗口class Close extends WindowAdapter{Danliao danliao;public Close(Danliao danliao){this.danliao=danliao;}public void windowClosing(WindowEvent e) {danliao.setVisible(false);}}。

java编写的简单局域网聊天室(适合初学者).

java编写的简单局域网聊天室(适合初学者).

import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color;import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.Panel; import java.awt.Point; import java.awt.TextArea; importjava.awt.TextField;import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File;import java.io.FileWriter; import java.io.IOException;import .DatagramPacket; import .DatagramSocket; import.InetAddress;import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class GUI_Chat extends Frame {private static final long serialVersionUID = 1L;private TextArea viewTextArea = new TextArea(20, 1; private TextArea sendTextArea = new TextArea(; private TextField ipTextField = new TextField(20; private Button sendButton = new Button(" 发送" ; private Button clearButton = new Button(" 清屏" ; private Button logButton = new Button(" 记录" ; private Button shakeButton = new Button(" 震动" ; private Panel panel = new Panel(; private DatagramSocket socket ;private Lock lock = new ReentrantLock(; private FileWriter fw ;public GUI_Chat( throws Exception {socket = new DatagramSocket(20000;fw = new FileWriter("log.txt" , true ;generateUI(; addListener(;new ReceiveThread(.start(;// 开启接收数据的线程}private void generateUI( { setTitle("GUI 聊天室" ; setSize(400, 600; setLocation(600, 50;setMinimumSize(new Dimension(400, 600; // 设置最小尺寸Font font = new Font("Courier New", Font.PLAIN , 15;viewTextArea .setFont(font; // 设置字体viewTextArea .setEditable(false ; // 设置不可编辑(会改变背景色viewTextArea .setBackground(Color.WHITE ; // 设置背景色add(viewTextArea , BorderLayout.NORTH ; // 把viewTextArea 放在上面sendTextArea .setFont(font;add(sendTextArea , BorderLayout.CENTER ; // 把sendTextArea 放在中间panel .add(ipTextField ; panel .add(sendButton ; panel .add(clearButton ; panel .add(logButton ;panel .add(shakeButton ;add(panel , BorderLayout.SOUTH ;// 把Panel 放在下面}private void addListener( { addWindowListener(new WindowAdapter( { // 关闭窗体public void windowClosing(WindowEvent e { try {fw .close(;} catch (IOException e1 { e1.printStackTrace(; }System. exit (0; } };sendButton .addActionListener(new ActionListener( { // 发送功能public void actionPerformed(ActionEvent e {send(;} };sendTextArea .addKeyListener(new KeyAdapter( { // 处理快捷键 public void keyPressed(KeyEvent e {if (e.isControlDown( && e.getKeyCode( == KeyEvent. VK_ENTER ||e.isAltDown( && e.getKeyCode( == KeyEvent.VK_S { send(; e.consume(; // 取消当前事件 } } };clearButton .addActionListener(new ActionListener( { // 清屏功能 public void actionPerformed(ActionEvent e { viewTextArea .setText("" ; } };logButton .addActionListener(new ActionListener( { // 聊天记录public void actionPerformed(ActionEvent e { showLog(; } };shakeButton .addActionListener(new ActionListener( { public void actionPerformed(ActionEvent e { sendShake(; } }; }private void sendShake( { try {String ip = ipTextField .getText(; sendData(ip, new byte [] { -1 }; // 向执行IP 发送一个特殊的消息 } catch (Exception e { e.printStackTrace(; }}private void showLog( {try (Scanner scanner = new Scanner(new File("log.txt" ;{ viewTextArea .setText("" ; // 清屏fw .flush(;// 把未保存的数据写入文件while (scanner.hasNextLine( // 如过文件中有数据就进入循环viewTextArea .append(scanner.nextLine( + "\r\n"; // 从文件读取一行, 追加到viewTextArea 中} catch (Exception e { e.printStackTrace(; } }private void send( { try { String msg = sendTextArea .getText(; // 获取要发的内容String ip = ipTextField .getText(; // 获取目标地址ip = ip.trim(.length( == 0 ? "255.255.255.255" : ip;String content = getTime( + " 我对 <" + (ip.equals("255.255.255.255" ? " 所有人" : ip + "> 说: \r\n" + msg + "\r\n\r\n";lock .lock(; // 开始同步 sendData(ip, msg.getBytes(; // 发送数据sendTextArea .setText("" ; // 清空viewTextArea .append(content; // 把要显示的内容追加到viewTextArea 中fw .write(content; // 保存聊天记录 lock .unlock(; // 结束同步 } catch (Exception e { e.printStackTrace(; } }private void sendData(String ip, byte [] data throws Exception { DatagramPacket packet = new DatagramPacket(data, data. length , InetAddress. getByName (ip, 20000; socket .send(packet;// UDP发送数据}private String getTime( { Date date = new Date(;SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"; return sdf.format(date; // 返回当前时间字符串 }private class ReceiveThread extends Thread { public void run( {DatagramPacket packet = new DatagramPacket(new byte [8192], 8192; while (true { try {socket .receive(packet;byte [] arr = packet.getData(; int length = packet.getLength(;String s = new String(arr, 0, length; // 接收到的字符串String ip = packet.getAddress(.getHostAddress(;String content = getTime( + " <" + ip + "> 对我说:\r\n" + s + "\r\n\r\n"; // 在viewTextArea 中显示的内容if (length == 1 && arr[0] == -1 { // 判断是否收到震动消息 doShake(; // 震动(改变位置 continue ; // 进入下一次循环 }lock .lock(; // 开始同步viewTextArea .append(content;fw .write(content; // 保存聊天记录 lock .unlock(;// 结束同步} catch (IOException e { e.printStackTrace(; }}}}private void doShake( { //震动方法 (通过改变窗体的位置实现 try {Point point = getLocation(; for (int i = 0; i < 5; i++ { Thread. sleep (30;setLocation(point.x + 5, point.y ; Thread. sleep (30;setLocation(point.x - 5, point.y + 5; }setLocation(point;} catch (InterruptedException e { e.printStackTrace(; } }public static void main(String[] args throws Exception { new GUI_Chat(.setVisible(true ; }}。

Java课程设计聊天室(含代码)

Java课程设计聊天室(含代码)

Java程序课程设计任务书JAVA聊天室的系统的设计与开发1.主要内容:用JA V A实现基于C/S模式的聊天室系统。

聊天室分为服务器端和客户端两部分,服务器端程序主要负责侦听客户端发来的信息,客户端需要登陆到服务器端才可以实现正常的聊天功能。

2.具体要求(包括技术要求等):系统的功能要求:A.服务器端主要功能如下:1.在特定端口上进行侦听,等待客户端连接。

2.用户可以配置服务器端的侦听端口,默认端口为8888。

3.向已经连接到服务器端的用户发送系统消息。

4.统计在线人数。

5.当停止服务时,断开所有的用户连接。

B.客户端的主要功能如下:1.连接到已经开启聊天服务的服务器端。

2.用户可以配置要连接的服务器端的IP地址和端口号。

3.用户可以配置连接后显示的用户名。

4.当服务器端开启的话,用户可以随时登录和注销。

5.用户可以向所有人或某一个人发送消息。

学习并掌握一下技术:Java JavaBean 等熟练使用一下开发工具:Eclipse,JCreator 等实现系统上诉的功能。

3.进度安排:12月28日~ 12月29日:课程设计选题,查找参考资料12月30日~ 1月1日:完成系统设计1月2日~ 1月5日:完成程序代码的编写1月6日:系统测试与完善1月7日:完成课程设计报告,准备答辩4.主要参考文献:[1].张广彬孟红蕊张永宝.Java课程设计(案例精编)[M].清华大学出版社.2007年版摘要在网络越来越发达的今天,人们对网络的依赖越来越多,越来越离不开网络,由此而产生的聊天工具越来越多,例如,国外的ICQ、国内腾讯公司开发的OICQ。

基于Java网络编程的强大功能,本次毕业设计使用Java编写一个聊天系统。

一般来说,聊天工具大多数由客户端程序和服务器程序外加服务器端用于存放客户数据的数据库组成,本系统采用客户机/服务器架构模式通过Java提供的Soket类来连接客户机和服务器并使客户机和服务器之间相互通信,由于聊天是多点对多点的而Java提供的多线程功能用多线程可完成多点对多点的聊天,数据库管理系统用SQL Server2000完成并通过JDBC-ODBC桥访问数据库。

java聊天室部分主要代码

java聊天室部分主要代码

ChatClient.javaimport java.awt.*;import java.io.*;import .*;import java.applet.*;import java.util.Hashtable;public class ChatClient extends Applet implements Runnable{ Socket socket=null;DataInputStream in=null;//读取服务器端发来的消息DataOutputStream out=null;//向服务器端发送的消息InputInfo 用户名提交界面=null;UserChat 聊天界面=null;Hashtable listTable;//用于存放在线用户的用户名的散列表Label 提示条;Panel north,center;Thread thread;public void init(){setSize(1000,800);int width=getSize().width;int height=getSize().height;listTable=new Hashtable();setLayout(new BorderLayout());用户名提交界面=new InputInfo(listTable);int h=用户名提交界面.getSize().height;聊天界面=new UserChat("",listTable,width,height-(h+5));聊天界面.setVisible(false);提示条=new Label("正在连接到服务器...",Label.CENTER);提示条.setForeground(Color.red);north=new Panel(new FlowLayout(FlowLayout.LEFT));center=new Panel();north.add(用户名提交界面);north.add(提示条);center.add(聊天界面);add(north,BorderLayout.NORTH);add(center,BorderLayout.CENTER);validate();}public void start(){if(socket!=null&&in!=null&&out!=null){try{socket.close();in.close();out.close();聊天界面.setVisible(false);}catch(Exception ee){}}try{socket=new Socket(this.getCodeBase().getHost(),6666);in=new DataInputStream(socket.getInputStream());out=new DataOutputStream(socket.getOutputStream());}catch(IOException ee){提示条.setText("连接失败");}//客户端成功连接服务器端if(socket!=null){InetAddress address=socket.getInetAddress();提示条.setText("连接:"+address+"成功");用户名提交界面.setSocketConnection(socket,in,out);north.validate();}if(thread==null){thread=new Thread(this);thread.start();}}public void stop(){try{socket.close();thread=null;}catch(IOException e){this.showStatus(e.toString());}}public void run(){while(thread!=null){if(用户名提交界面.getchatornot()==true){聊天界面.setVisible(true);聊天界面.setName(用户名提交界面.getName());聊天界面.setSocketConnection(socket,in,out);提示条.setText("祝聊天快乐!");center.validate();break;}try{Thread.sleep(100);}catch(Exception e){}}}}ChatMain.javaimport .*;import java.util.*;public class ChatMain {public static void main(String args[]) {ServerSocket server=null;Socket you=null;Hashtable peopleList;peopleList=new Hashtable();while(true){try{//服务器端在端口6666处监听来自客户端的信息server=new ServerSocket(6666);}catch(IOException e1){System.out.println("正在监听");}try{//当服务器端接收到客户端的消息后,取得客户端的IP地址。

java多功能聊天室代码

java多功能聊天室代码

package v5;//客户端代码import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.IOException;import .Socket;import .UnknownHostException;import java.util.List;import javax.swing.JButton;import javax.swing.JCheckBox;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;public class ClientFrame extends JFrame implements ActionListener,Runnable { JLabel jlMsg, jlTitle;JTextField jtfMsg;JTextArea jtaContent;// 内容JTextArea jtaList;// 在线人员列表JButton btnStart, btnShutdown, btnSend;JPanel jpControl, jp2, jpCenter;JComboBox jcbAll;JCheckBox jckS;// 私聊Socket socket = null;String nickname;public ClientFrame() {// 初始化组件createFrame();// 设置窗体this.setTitle("聊天室客户端");this.setSize(600, 320);this.setLocation(100, 140);this.setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 注册监听器btnStart.addActionListener(this);btnSend.addActionListener(this);jtfMsg.addActionListener(this);}/*** 初始化组件*/public void createFrame() {jlMsg = new JLabel("对");jlTitle = new JLabel("欢迎进入聊天室。

java聊天程序代码

java聊天程序代码

import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.io.*;public class ChatJFrame extends JFrame implements ActionListener {private JTextArea text_receiver; //显示对话内容的文本区private JTextField text_sender; //输入发送内容的文本行private PrintWriter cout; //字符输出流对象private String name; //网名public ChatJFrame(String name, String title, PrintWriter cout) //构造方法{super("聊天室"+name+" "+title);this.setSize(320,240);this.setLocation(300,240);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.text_receiver = new JTextArea();this.text_receiver.setEditable(false); //不可编辑this.add(this.text_receiver);JPanel panel = new JPanel();this.add(panel,"South");this.text_sender = new JTextField(12);panel.add(this.text_sender);this.text_sender.addActionListener(this); //注册单击事件监听器JButton button_send = new JButton("发送");panel.add(button_send);button_send.addActionListener(this);JButton button_leave = new JButton("离线");panel.add(button_leave);button_leave.addActionListener(this);this.setVisible(true);this.setWriter(cout); = name;}public ChatJFrame(){this("","",null);}public void setWriter(PrintWriter cout) //设置字符输出流对象{this.cout = cout;}public void receive(String message) //显示对方发来的内容{text_receiver.append(message+"\r\n");}public void actionPerformed(ActionEvent e){if (e.getActionCommand()=="离线"){if (this.cout!=null){this.cout.println(name+"离线");this.cout.println("bye");this.cout = null;}text_receiver.append("我离线\n");}else //发送{if (this.cout!=null){this.cout.println(name+" 说:"+text_sender.getText());text_receiver.append("我说:"+text_sender.getText()+"\n"); text_sender.setText("");}elsetext_receiver.append("已离线,不能再发送。

java实现聊天室功能(包含全部代码-有界面)

java实现聊天室功能(包含全部代码-有界面)

服务器端代码:import .*;import .*;import .*;import .*;public class Server{private static final int PORT=6666;G_Menu gm=new G_Menu();private ServerSocket server;public ArrayList<PrintWriter> list;public static String user;public static ArrayList<User> list1=new ArrayList<User>();....");while(true){Socket client=();etServer();}class Chat implements Runnable{Socket socket;private BufferedReader br;private String msg;private String mssg="";public Chat(Socket socket){try{=socket;}catch(Exception ex){();}}public void run(){try{br=new BufferedReader(new InputStreamReader()));while((msg=())!=null){if("1008611"))plit(":");quals()+"("+()+")"))etOutputStream());quals ()))etOutputStream());quals(si[0]))lose();;import .*;import .*;import class Socket_one;import .*;import .*;import Landen extends Frame implements ActionListener {JFrame jf=new JFrame("聊天登陆");JPanel jp1=new JPanel();JPanel jp2=new JPanel();JPanel jp3=new JPanel();JPanel jp4=new JPanel();JLabel jl1=new JLabel("姓名:");JLabel jl2=new JLabel("地址:");JLabel jl3=new JLabel("端口:");JRadioButton jrb1=new JRadioButton("男生"); JRadioButton jrb2=new JRadioButton("女生"); JRadioButton jrb3=new JRadioButton("保密");public JTextField jtf1=new JTextField(10);public JTextField jtf2=new JTextField(10);public JTextField jtf3=new JTextField(10);JButton jb1=new JButton("连接");JButton jb2=new JButton("断开");TitledBorder tb=new TitledBorder("");ButtonGroup gb=new ButtonGroup();public void init()quals("断开")){(0);}if().equals("连接")){if().equals("")){(null,"请输入用户名!");}else if(!()&&!()&&!()){(null,"请选择性别!");}else{(false);if()){s1="boy";}else if()){s1="girl";}else if()){s1="secret";}G_Menu gmu=new G_Menu();(),s1);();}}}}public class Login{public static void main(String[] args) {new Landen().init();}}主界面代码:import .*;import .*;import .*;import .*;class G_Menu extends JFrame implements ActionListener {JFrame jf=new JFrame("聊天室");public Socket_one soc;public PrintWriter pw;public JPanel jp1=new JPanel();public JPanel jp2=new JPanel();public JPanel jp3=new JPanel();public JPanel jp4=new JPanel();public JPanel jp5=new JPanel();public JPanel jp6=new JPanel();public JPanel jp7=new JPanel();public static JTextArea jta1=new JTextArea(12,42); public static JTextArea jta2=new JTextArea(12,42);public JLabel jl1=new JLabel("对");public static JComboBox jcomb=new JComboBox();public JCheckBox jcb=new JCheckBox("私聊");public JTextField jtf=new JTextField(36);public JButton jb1=new JButton("发送>>");public JButton jb2=new JButton("刷新");public static DefaultListModel listModel1;public static JList lst1;public String na;public String se;public String message;public void getMenu(String name,String sex)quals("发送>>"))quals("")) {if()){String name1=(String)();message="悄悄话"+na+"("+se+")"+"对"+name1+"说:"+();("4");quals("刷新"));import .*;import .*;class User{private String name;//用户姓名private String sex;//用户性别private Socket sock;//用户自己的socketpublic User(String name,String sex,Socket sock){setName(name);setSex(sex);setSock(sock);}public String getName(){return name;}public void setName(String name){=name;}public String getSex(){return sex;}public void setSex(String sex){=sex;}public Socket getSock(){return sock;}public void setSock(Socket sock){=sock;}}使用说明:1、先将所有的类都编译一下2、先运行服务器端代码3、再运行登录界面代码。

JAVA实例(swing聊天室)源代码一服务端源码

JAVA实例(swing聊天室)源代码一服务端源码
ps.println(reStr);
ps.flush();
}
}
Socket s=ss.accept();
allSocket.add(s);
aSocket.put(s, String.&#118alueOf(i));
System.out.println(reStr);
}
for(Iterator iter=aSocket.keySet().iterator();iter.hasNext();){
try {
ServerSocket ss=new ServerSocket(8888);
int i=1;
while(true){
public static void main(String[] args) {
List<Socket> allSocket=new ArrayList<Socket>();
Map<Socket,String> aSocket=new HashMap<Socket,String>();
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
原文地址/操作时去掉此行
public class TcpQQServer {
String[] tempStr=reStr.split("-");
if("register".equals(tempStr[0])){
if(aSocket.containsKey(s)){

JAVA聊天室源码

JAVA聊天室源码

//聊天室服务器import .*;import java.io.*;import java.util.*;import java.awt.event.*;import java.awt.*;import javax.swing.*;class Server extends JFrame {private TextArea msgA = new TextArea();//服务器用来输入的文本域private TextArea area = new TextArea();//服务器显示消息的文本域private TextField portT = new TextField("8888");private java.awt.List list = new java.awt.List();//在线客户列表private ServerSocket server;//服务器private Socket client;//客户端private Map<String, Socket> container = new HashMap<String, Socket>();//HashMap void init() {//设置几个面板//Panel p1 = new Panel();Panel p2 = new Panel();Panel p3 = new Panel();Panel p4 = new Panel();Panel p5 = new Panel();Panel p6 = new Panel();Panel p7 = new Panel();Panel p8 = new Panel();Panel p9 = new Panel();Panel p10 = new Panel();//设置两个主要的文本框Label lb1 = new Label("服务器界面");lb1.setBackground(new Color(250,120,150));Label lb2 = new Label("port");BorderLayout border1 = new BorderLayout();p1.setLayout(border1);p1.add(BorderLayout.CENTER, area);BorderLayout border2 = new BorderLayout();p5.setLayout(border2);p5.add(BorderLayout.NORTH, p3);p5.add(BorderLayout.CENTER, msgA);BorderLayout border3 = new BorderLayout();p7.setLayout(border3);p7.add(BorderLayout.CENTER, p1);p7.add(BorderLayout.SOUTH, p5);p7.setBackground(new Color(250,150,200));JButton startButton = new JButton("启动服务");JButton sendButton = new JButton("发送");JButton flushButton = new JButton("刷新列表");FlowLayout fl = new FlowLayout(FlowLayout.LEFT); p8.setLayout(fl);p8.add(lb2);p8.add(portT);p8.add(startButton);p8.add(sendButton);p8.add(flushButton);p8.setBackground(new Color(250,120,150));BorderLayout border4 = new BorderLayout();p9.setLayout(border4);p9.add(BorderLayout.CENTER, p7);p9.add(BorderLayout.SOUTH, p8);p10.setLayout(new BorderLayout());Label lb3 = new Label("在线用户");lb3.setBackground(new Color(250,120,150));p10.add(lb3,BorderLayout.NORTH);p10.add(list,BorderLayout.CENTER);area.setEditable(false);BorderLayout border = new BorderLayout();this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent arg0) {System.exit(0);}});this.setLayout(border);this.add(BorderLayout.NORTH, lb1);this.add(BorderLayout.CENTER, p9);this.add(BorderLayout.EAST, p10);this.setTitle("聊天服务器 ");this.setBounds(100, 100, 600, 550);this.setVisible(true);//"启动服务"按钮监听器startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {Thread t = new Start();t.start();}});//启动按钮监听器----end//发送按钮监听器sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {String msg = msgA.getText();if (msg != null && msg != "") {//如果消息不为空Calendar ca = new GregorianCalendar();int hh = ca.get(Calendar.HOUR_OF_DAY);int mm = ca.get(Calendar.MINUTE);int ss = ca.get(Calendar.SECOND);String time = new String(hh + ":" + mm + ":" + ss + " ");broadcast(time + "[系统消息]: " + msg);//那么广播这条系统消息area.append(time + "[系统消息]: " + msg + "\n");msgA.setText("");}}});//end//刷新按钮监听器flushButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if (list != null) {list.removeAll();//清空在线用户列表,以便刷新}Set<Map.Entry<String, Socket>> mySet = container.entrySet();for (Iterator<Map.Entry<String, Socket>> it = mySet.iterator(); it.hasNext();) {//刷新列表 Map.Entry<String, Socket> me = it.next();String aClientName = me.getKey();Socket aClient = me.getValue();String aClientAddress = aClient.getInetAddress().getHostAddress();list.add(aClientName + "----" + aClientAddress);}//end of for}//end of actionPerformed});//endmsgA.addKeyListener(new KeyAdapter(){//键盘监听器---按下Enter发送信息public void keyPressed(KeyEvent e){int value = e.getKeyCode();if(value == KeyEvent.VK_ENTER){String msg = msgA.getText();Calendar ca = new GregorianCalendar();int hh = ca.get(Calendar.HOUR_OF_DAY);int mm = ca.get(Calendar.MINUTE);int ss = ca.get(Calendar.SECOND);String time = new String(hh + ":" + mm + ":" + ss + " ");broadcast(time + "[系统消息]: " + msg);//那么广播这条系统消息area.append(time + "[系统消息]: " + msg + "\n");msgA.setText("");}}});}//end of init()class Start extends Thread //启动服务器的线程{public void run() {try {if(server != null && !server.isClosed()){area.append("警告!服务器已在启动中!\n");}else{server = new ServerSocket(Integer.parseInt(portT.getText()));//启动服务器area.append((new Date()).toString() +'\n'+ "[恭喜!^_^]"+"服务器启动成功!" + "\n\n"); }while(true){client = server.accept();Thread sgS = new SgService(client);//为每位登录的客户创建一个线程sgS.start();//启动客户线程}}catch (Exception e) {System.out.println("cuowu 1");e.printStackTrace();}}//end of run()} //end of Start//处理单个客户的线程class SgService extends Thread//SgService---begin{private Socket client = null;//客户套接字private BufferedReader br = null;//输入流private PrintStream ps = null;private int counter = 0;//记录是第几次接受用户的信息private int mark = 0;//记录用户说不文明用语的次数private String name = null;SgService(Socket client) {//构造方法this.client = client;public void run() {//run()----begintry {br = new BufferedReader(new InputStreamReader(client.getInputStream()));ps = new PrintStream(client.getOutputStream());String msg = null;while ((msg = br.readLine()) != null) {//无限循环,意味着可以和客户进行无限次交互if(counter == 0){name = msg;container.put(name,client);list.add(name + "----" + client.getInetAddress().getHostAddress());Calendar ca = new GregorianCalendar();int hh = ca.get(Calendar.HOUR_OF_DAY);int mm = ca.get(Calendar.MINUTE);int ss = ca.get(Calendar.SECOND);String time = hh + ":" + mm + ":" + ss + " ";broadcast(time + name + "上线了!");area.append(time + name + "上线了!\n\n");counter ++;}else{if(msg.equals("你是个笨蛋")){mark = mark + 1;if(mark < 3){Calendar ca = new GregorianCalendar();int hh = ca.get(Calendar.HOUR_OF_DAY);int mm = ca.get(Calendar.MINUTE);int ss = ca.get(Calendar.SECOND);String time = new String(hh + ":" + mm + ":" + ss + " ");singleCom(time +"[系统消息]: 警告!请注意文明用语!" ,client);//在服务器端显示这个用户说不文明语言的次数area.append(time + "[系统消息]: " + name +"第" + mark+ "次使用了不文明用语,特此警告!");}else{//如果客户第三次说不文明的话,系统就把他踢出聊天室Calendar ca = new GregorianCalendar();int hh = ca.get(Calendar.HOUR_OF_DAY);int mm = ca.get(Calendar.MINUTE);int ss = ca.get(Calendar.SECOND);String time = new String(hh + ":" + mm + ":" + ss + " ");if(mark == 3){singleCom(time + "[系统消息]: 由于您多次使用了不文明用语,经警告无效,现已被踢出聊天室!" ,client);//告诉他本人}removeClient(name,client);//从系统列表中删除这个人的信息//并向所有人广播这一消息broadcast(time + "[系统消息]: " + name + "由于多次使用了不文明用语,经警告无效,现已被踢出聊天室!");area.append(time + "[系统消息]: " + name + "由于多次使用了不文明用语,经警告无效,现已被踢出聊天室!\n");}}else{Calendar ca = new GregorianCalendar();int hh = ca.get(Calendar.HOUR_OF_DAY);int mm = ca.get(Calendar.MINUTE);int ss = ca.get(Calendar.SECOND);String time = new String(hh + ":" + mm + ":" + ss + " ");area.append(time + name+"说:"+msg + "\n\n");//将客户发送的消息显示在服务器的窗口中broadcast(time + name+"说:"+msg+"\n");//同时向每个在线客户广播这则消息}}}//end of while}catch (Exception ex) {Calendar ca = new GregorianCalendar();int hh = ca.get(Calendar.HOUR_OF_DAY);int mm = ca.get(Calendar.MINUTE);int ss = ca.get(Calendar.SECOND);String time = new String(hh + ":" + mm + ":" + ss + " ");area.append(time + name + "下线了!\n");broadcast(time + name + "下线了!\n");list.remove(name + "----" + client.getInetAddress().getHostAddress());container.remove(name);}}//run()---end}//SgService-----endvoid removeClient(String name,Socket client){//踢人list.remove(name + "----" + client.getInetAddress().getHostAddress());container.remove(name);}//广播void broadcast(String msg) {//broadcast()-----beginSet<Map.Entry<String, Socket>> mySet = container.entrySet();Iterator<Map.Entry<String, Socket>> it = mySet.iterator();String message = msg;while (it.hasNext()) {//如果列表中还有客户Map.Entry<String, Socket> me = it.next();Socket tempClient = me.getValue();singleCom(message, tempClient);//就把消息向发给这个客户}}//broadcast()-----end//向单个客户发送消息private void singleCom(String msg, Socket aClient) {//singleCommunication------begintry {PrintStream pw = new PrintStream(aClient.getOutputStream());String message = msg;pw.println(msg);} catch (Exception ex) {ex.printStackTrace();}}//singleCommunication----endpublic static void main(String[] args) {new Server().init(); //启动服务器窗口System.out.println("服务器:");}}//end of Server//登录界面:import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import .*;class Login extends JFrame implements ActionListener {TextField txtPort;TextField txtIP;TextField txtName;JButton btnLogin;JButton btnCancel;Socket toServer;BufferedReader in;PrintStream out;public Login(){Panel p1=new Panel();Panel p2=new Panel();Panel p3=new Panel();Panel p4=new Panel();Panel p5=new Panel();Label l1=new Label("port");Label l2=new Label("IP");Label l3=new Label("昵称");txtPort=new TextField("8888",15);txtIP=new TextField("192.168.55.1",15);txtName=new TextField("小敏",15);p2.add(l1);p2.add(txtPort);p3.add(l2);p3.add(txtIP);p4.add(l3);p4.add(txtName);GridLayout g=new GridLayout(3,1);//三行一列的网格布局管理器p1.setLayout(g);//设置布局管理器p1.add(p2);//将组件添加到面板中p1.add(p3);p1.add(p4);p1.setBackground(new Color(100,250,100));//更改面板颜色btnLogin=new JButton("登陆");btnCancel=new JButton("取消");btnLogin.addActionListener(this);//添加监听器btnCancel.addActionListener(this);BorderLayout border1=new BorderLayout();//边界布局管理器this.setLayout(border1);p5.add(btnLogin);p5.add(btnCancel);this.add(BorderLayout.SOUTH,p5);this.add(BorderLayout.CENTER,p1);this.setSize(350,250);this.setTitle("用户登录");this.setResizable(false);this.setLocation(450,250);this.setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口}//实现"登录"和"取消"按钮的监听器public void actionPerformed(ActionEvent e){JButton button = (JButton)e.getSource();if(button.equals(btnCancel)){dispose();//如果客户按了"取消"按钮,那么登录窗口就关闭}else {//如果客户按了"登录",那么就连接服务器LoginStart ls = new LoginStart();ls.start();this.dispose();}}class LoginStart extends Thread{public void run(){int port = Integer.parseInt(txtPort.getText());//取得端口号String ip = txtIP.getText();//取得要连接的服务器的IP地址String name = txtName.getText();//取得客户姓名try {toServer = new Socket(ip,port); //连接服务端 socket("主机名",端口号);in = new BufferedReader(new InputStreamReader(toServer.getInputStream())); //建立输入流out = new PrintStream(toServer.getOutputStream());//输出流new Client(out,in,name);//如果登录成功,则弹出客户端聊天窗口dispose(); //同时关闭登录窗口}catch (Exception e2) {System.out.println("登录失败!");//如果登录失败,则打印出"登录失败",以告知客户e2.printStackTrace();}}}public static void main(String[] args){new Login();//启动登录窗口}}//聊天室客户端import java.awt.event.*;import javax.swing.*;import java.io.*;import .*;import java.awt.*;class Client extends JFrame{PrintStream out; //输出流BufferedReader in; //输入流String name;TextArea area = new TextArea();TextArea msgA = new TextArea();TextField frdNameT = new TextField(10);List list =new List();Panel p10=new Panel();JButton sendButton = new JButton("发送");JButton closeButton = new JButton("关闭");JButton jb1 = new JButton("设置背景颜色");JButton jb2 = new JButton("设置字体颜色");Label lb1 = new Label("昵称:");void init(){this.pack();//设置几个面板Panel p1=new Panel();Panel p2=new Panel();Panel p3=new Panel();Panel p4=new Panel();Panel p5=new Panel();Panel p6=new Panel();Panel p7=new Panel();Panel p8=new Panel();Panel p9=new Panel();lb1.setBackground(Color.pink);//设置两个主要的文本框BorderLayout border1=new BorderLayout();p1.setLayout(border1);p1.add(BorderLayout.CENTER,area);area.setEditable(false);FlowLayout f2=new FlowLayout(FlowLayout.LEFT); p3.setLayout(f2);p3.add(jb1);p3.add(jb2);BorderLayout border2=new BorderLayout();p5.setLayout(border2);p5.add(BorderLayout.NORTH,p3);p5.add(BorderLayout.CENTER,msgA);p5.setBackground(Color.pink);BorderLayout border3=new BorderLayout();p7.setLayout(border3);p7.add(BorderLayout.CENTER,p1);p7.add(BorderLayout.SOUTH,p5);FlowLayout fl=new FlowLayout(FlowLayout.RIGHT); p8.setLayout(fl);p8.add(sendButton);p8.add(closeButton);p8.setBackground(Color.pink);BorderLayout border4=new BorderLayout();p9.setLayout(border4);p9.add(BorderLayout.CENTER,p7);p9.add(BorderLayout.SOUTH,p8);//窗口关闭this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent arg0) {System.exit(0);}});BorderLayout border5=new BorderLayout();p10.setLayout(border5);p10.add(BorderLayout.CENTER,list);p10.setBackground(Color.pink);//添加背景颜色的监听器jb1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){JColorChooser chooser4=new JColorChooser();Color color=chooser4.showDialog(Client.this,"我的调色盘",Color.yellow);area.setBackground(color);msgA.setBackground(color);list.setBackground(color);}});//添加字体颜色的监听器jb2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){JColorChooser chooser4=new JColorChooser();Color color=chooser4.showDialog(Client.this,"我的调色盘",Color.yellow);area.setForeground(color);msgA.setForeground(color);list.setForeground(color);}});BorderLayout border=new BorderLayout();this.setLayout(border);this.add(BorderLayout.NORTH,lb1);this.add(BorderLayout.CENTER,p9);this.add(BorderLayout.EAST,p10);this.setTitle("聊天室客户端");this.setSize(700,600);this.setVisible(true);sendButton.addActionListener(new ActionListener(){//"发送"按钮监听器public void actionPerformed(ActionEvent e){String msg = msgA.getText();msgA.setText("");//清空输入文本域out.println(msg);}});msgA.addKeyListener(new KeyAdapter(){//键盘监听器---按下Enter发送信息 public void keyPressed(KeyEvent e){int value = e.getKeyCode();if(value == KeyEvent.VK_ENTER){String msg = msgA.getText();msgA.setText("");//清空输入文本域out.println(msg);}}});closeButton.addActionListener(new ActionListener(){//"关闭"按钮监听器 public void actionPerformed(ActionEvent e){System.exit(100);}});}//end of init()public Client(PrintStream out,BufferedReader in,String name) {//构造方法 this.out = out;this.in = in; = name;lb1.setText("昵称:"+ name);init();//弹出客户端窗口out.println(name);receive();//开始与服务器通信}public void receive() { //接受服务端发来的信息。

java简单的聊天窗口代码

java简单的聊天窗口代码

要创建一个简单的Java聊天窗口,您可以使用Java的图形用户界面(GUI)工具包Swing。

以下是一个基本的聊天窗口示例:```javaimport javax.swing.*;import java.awt.*;import java.awt.event.*;public class ChatWindow extends JFrame implements ActionListener {private JTextField inputField;private JTextArea chatArea;private String message = "";public ChatWindow() {super("简单聊天窗口");setSize(400, 300);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);inputField = new JTextField();chatArea = new JTextArea();JButton sendButton = new JButton("发送");sendButton.addActionListener(this);JScrollPane scrollPane = new JScrollPane(chatArea);chatArea.setAutoscrolls(true);getContentPane().add(inputField,BorderLayout.SOUTH);getContentPane().add(sendButton, BorderLayout.EAST); getContentPane().add(scrollPane,BorderLayout.CENTER);}public void actionPerformed(ActionEvent e) {if (e.getSource() == sendButton) {message += inputField.getText() + "\n";chatArea.append(inputField.getText() + "\n");inputField.setText(""); // 清空输入框}}public static void main(String[] args) {ChatWindow chatWindow = new ChatWindow();}}```这个程序创建了一个简单的聊天窗口,用户可以在输入框中输入消息,然后点击"发送"按钮将消息发送到聊天区域。

利用JAVA实现简单聊天室

利用JAVA实现简单聊天室

利用JAVA实现简单聊天室1.设计思路Java是一种简单的,面向对象的,分布式的,解释的,键壮的,安全的,结构中立的,可移植的,性能很优异的,多线程的,动态的语言。

而且,Java 很小,整个解释器只需215K的RAM。

因此运用JAVA程序编写聊天室,实现简单聊天功能。

程序实现了聊天室的基本功能,其中有:(1)启动服务器:实现网络的连接,为注册进入聊天室做准备。

(2)注册登陆界面:填写基本信息如姓名等,可以供多人进入实现多人聊天功能。

(3)发送信息:为用户发送信息提供平台。

(4)离开界面:使用户退出聊天室。

(5)关闭服务器:断开与网络的连接,彻底退出聊天室。

2.设计方法在设计简单聊天室时,需要编写5个Java源文件:Server.java、Objecting.java、LogIn.java、ClientUser.java、Client.java。

3 程序功能图及程序相关说明(1)主功能框图(2) 聊天室基本功能表4.程序代码是说明程序中引入的包:package Chat; import .*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.io.*;(1)服务器端代码中用户自定义类:类名:Server作用:服务器启动继承的接口名:ActionListenerpublic class Server implements ActionListener{定义的对象:count //记录点机关闭按钮次数2次关闭soconly //只有SOCKET,用于群发sockets//所有客户的SOCKETsocket_thread //Socket所在的线乘,用于退出;frame // 定义主窗体panel //定义面板start,stop //启动和停止按钮主要成员方法:public void center //定义小程序查看器的位置public void actionPerformed //定义处理异常机制定义子类:serverRun,Details继承的父类名:Threadclass serverRun extends Thread //启线乘用于接收连入的Socket class Details extends Thread //具体处理消息的线乘,只管发送消息创建一个ServerSocket 对象,用于接受指定端口客户端的信息ServerSocket server = new ServerSocket("1234");接受请求时候,通过accept()方法,得到一个socket对象。

Java聊天室代码

Java聊天室代码

基于UDP的简单java聊天室代码./***这个一个简单的利用数据报协议传送信息的聊天测试程序。

*程序由三个简单的组件构成,分别是一个List,用于接收信息,*一个JComboBox,用于输入对方ip地址,和一个JTextField,*用于编辑信息。

<br>*聊天双方的程序必须监听同一个固定的端口,只有这样才能实现*相互通信。

当输入的ip地址为localhost时,自己会收到自己*发送的信息。

*/package chat;import java.util.*;import .*;import java.io.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Chat extends JFrame{PrintStream ps=null;private int port;//端口java.awt.List list=new java.awt.List(20);//接收信息列表Vector vector=new Vector();//已发IP列表JComboBox ipField=new JComboBox(vector);//发送对象ip JTextField textField=new JTextField(20);//编辑发送内容组件DatagramSocket socket=null;/*** Method Chat***/public Chat(int port) {// TODO: 在这添加你的代码this.port=port;try{ps=new PrintStream("log.txt");}catch(FileNotFoundException e){e.printStackTrace();}try{socket=new DatagramSocket(port);}catch(Exception e){e.printStackTrace(ps);}Container contentPane=this.getContentPane();ipField.setPreferredSize(new Dimension(120,20));ipField.setEditable(true);JPanel panel=new JPanel();panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS));contentPane.add(list,BorderLayout.CENTER);contentPane.add(panel,BorderLayout.SOUTH);panel.add(ipField);panel.add(textField);receive();addListener();}/***加入并处理事件听侦*/void addListener(){//当在textField组件中输入内容后按下回车键,即发送出输入信息。

SimpleChatRoom(简易聊天室代码)

SimpleChatRoom(简易聊天室代码)

package test3;//服务器类import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import .ServerSocket;import .Socket;import java.util.ArrayList;import java.util.Iterator;public class VerySimpleChatServer {ArrayList clientOutputStream;public class ClientHandler implements Runnable{BufferedReader reader;Socket sock;public ClientHandler(Socket clientSocket){try{sock = clientSocket;InputStreamReader isReader = new InputStreamReader(sock.getInputStream());reader = new BufferedReader(isReader);}catch(Exception e){e.printStackTrace();}}public void run(){String message;try{while((message = reader.readLine())!=null){System.out.println("read "+message);tellEveryone(message);}}catch(Exception e){e.printStackTrace();}}}public void go(){clientOutputStream = new ArrayList();try{ServerSocket serverSock = new ServerSocket(5000);while(true){Socket clientSocket = serverSock.accept();PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());clientOutputStream.add(writer);Thread t = new Thread(new ClientHandler(clientSocket));t.start();System.out.println("got a connection");}}catch(Exception e){e.printStackTrace();}}public void tellEveryone(String message){Iterator it = clientOutputStream.iterator();while(it.hasNext()){try{PrintWriter writer = (PrintWriter) it.next();writer.println(message);writer.flush();}catch(Exception e){e.printStackTrace();}}}public static void main(String[] args) {new VerySimpleChatServer().go();}}package test3;//聊天室类import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import .Socket;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;import javax.swing.ScrollPaneConstants;public class SimpleChatClient {JTextArea input;JTextField output;BufferedReader reader;PrintWriter writer;Socket sock;public void go(){JFrame frame = new JFrame("简易聊天室");JPanel mainPanel = new JPanel();input = new JTextArea(15,50);input.setLineWrap(true);input.setWrapStyleWord(true);input.setEditable(false);JScrollPane qScroller = new JScrollPane(input);qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL _SCROLLBAR_ALWAYS);qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZO NTAL_SCROLLBAR_NEVER);output = new JTextField(20);JButton sendButton = new JButton("send");sendButton.addActionListener(new SendButtonListener());mainPanel.add(qScroller);mainPanel.add(output);mainPanel.add(sendButton);setUpNetworking();Thread readerThread = new Thread(new IncomingReader());readerThread.start();frame.getContentPane().add(BorderLayout.CENTER,mainPanel);frame.setSize(600,400);frame.setVisible(true);}private void setUpNetworking(){try{sock = new Socket("127.0.0.1",5000);InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());reader = new BufferedReader(streamReader);writer = new PrintWriter(sock.getOutputStream());System.out.println("networking established");}catch(IOException e){e.printStackTrace();}}public class SendButtonListener implements ActionListener{@Overridepublic void actionPerformed(ActionEvent e) {try{writer.println(output.getText());writer.flush();}catch(Exception ex){ex.printStackTrace();}output.setText("");output.requestFocus();}}public class IncomingReader implements Runnable{public void run(){String message;try{while((message = reader.readLine())!=null){System.out.println("read "+message);input.append(message+"\n");}}catch(Exception e){e.printStackTrace();}}}public static void main(String[] args) {SimpleChatClient client = new SimpleChatClient();client.go();}}。

java_课程设计_聊天窗口

java_课程设计_聊天窗口

java_课程设计_聊天窗口JAVA课程设计----------聊天窗口姓名:学号:班级:计科2老师:赵宏宇设计了一个简单的聊天室程序,用于实现聊天室的基本功能,分为了客户端和服务器端,服务器端可以接收多个连接,客户端可以连接服务器。

客户端发送消息给服务器端,服务器接收消息,转发给所有的客户。

一、源程序代码服务器端源代码,ServerTest.javaimport java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.DataInput;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import .ServerSocket;import .Socket;import java.util.Enumeration;import java.util.Vector;import com.sun.corba.se.spi.activation.ServerHeldDown;public class ServerTest {public ServerTest(int port) throws IOException{ServerSocket server=new ServerSocket(port);while(true){Socket conn=server.accept();DataInputStream inputStream = new DataInputStream(conn.getInputStream());String who=inputStream.readUTF();System.out.print("Clinet"+"(IP"+conn.getInetAddress()+")"+ who+"enter!"+"\n");ServerHander cn=new ServerHander(who,conn);cn.start();}}public static void main(String[] args)throws IOException {new ServerTest(9001);// TODO Auto-generated method stub}}class ServerHander extends Thread{Socket socket;DataInputStream in;DataOutputStream out;String who;protected static Vectorclientlist=new Vector();public ServerHander(String name,Socket socket)throws IOExceptionthis.who=name;this.socket=socket;in=new DataInputStream(new BufferedInputStream(socket.getInputStream()));out=new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));}public void run(){try{clientlist.addElement(this);sendallclient("欢迎"+who+"进入聊天室");while(true){String msg=in.readUTF();sendallclient(who+"说:"+msg);}}catch(IOException e){System.out.println("Client exit or error.");}clientlist.removeElement(this);sendallclient(who+"退出!");try{socket.close();}catch (IOException ex)System.out.println("Connection has been closed");}}protected static void sendallclient(String msg){synchronized (clientlist) {Enumerationallclients=clientlist.elements();while(allclients.hasMoreElements()){ServerHander serh=(ServerHander)allclients.nextElement(); try{serh.out.writeUTF(msg);serh.out.flush();}catch(IOException exc){serh.interrupt();}}}}}客户端源程序,ClientTest.javaimport java.awt.BorderLayout;import java.awt.Frame;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import .Socket;public class ClientT est {public ServiceFrame sf;private Socket csocket;private DataInputStream in;private DataOutputStream out;public static void main(String[] args) {// TODO Auto-generated method stubString who="";BufferedReader in=new BufferedReader(new InputStreamReader(System.in));System.out.print("请输入你的名字");try{who=in.readLine().trim();}catch(IOException e){e.printStackTrace();}new ClientTest(who,"127.0.0.1",9001);}public ClientTest(String who,String server,int port){sf=new ServiceFrame("客户端聊天窗口");sf.sendFD.addKeyListener(new ActListener(this,sf));sf.addWindowListener(new ExitListener(this));try{csocket=new Socket(server,port);in=new DataInputStream(new BufferedInputStream(csocket.getInputStream()));out=new DataOutputStream(new BufferedOutputStream(csocket.getOutputStream()));out.writeUTF(who);out.flush();while(true){sf.showTA.append("--"+in.readUTF()+"\n");}}catch(Exception e){System.out.println("Server error!");this.close();System.exit(0);}}protected void send(String msg){try{out.writeUTF(msg);out.flush();}catch(IOException e){}}protected void close(){try{sf.dispose();out.close();in.close();}catch(IOException ex){}}}class ServiceFrame extends Frame {protected TextArea showTA; protected TextField sendFD;public ServiceFrame(String winnm) {super(winnm);setLayout(new BorderLayout());add("North",showTA=new TextArea()); showTA.setEditable(false);add("South",sendFD=new TextField()); pack();show();sendFD.requestFocus();}}class ActListener extends KeyAdapter{ClientTest client;ServiceFrame sframe;public ActListener(ClientTest c,ServiceFrame sf) {client=c;sframe=sf;}public void keyPressed(KeyEvent e){if(e.getKeyCode()==KeyEvent.VK_ENTER){ client.send(sframe.sendFD.getText()); sframe.sendFD.setText("");}}}class ExitListener extends WindowAdapter {ClientTest client;public ExitListener(ClientTest c){client=c;}public void windowClosing(WindowEvent e) {client.close();System.exit(0);}}二、运行结果截图先运行服务器端,在运行客户端。

java_聊天室源码

java_聊天室源码

java_聊天室源码【ClientSocketDemo.java 客户端Java源代码】import .*;import java.io.*;public class ClientSocketDemo{//声明客户端Socket对象socketSocket socket = null;//声明客户器端数据输入输出流DataInputStream in;DataOutputStream out;//声明字符串数组对象response,用于存储从服务器接收到的信息String response[];//执行过程中,没有参数时的构造方法,本地服务器在本地,取默认端口10745public ClientSocketDemo(){try{//创建客户端socket,服务器地址取本地,端口号为10745socket = new Socket("localhost",10745);//创建客户端数据输入输出流,用于对服务器端发送或接收数据in = new DataInputStream(socket.getInputStream());out = new DataOutputStream(socket.getOutputStream());//获取客户端地址及端口号String ip = String.valueOf(socket.getLocalAddress());String port = String.valueOf(socket.getLocalPort());//向服务器发送数据out.writeUTF("Hello Server.This connection is from client.");out.writeUTF(ip);out.writeUTF(port);//从服务器接收数据response = new String[3];for (int i = 0; i < response.length; i++){response[i] = in.readUTF();System.out.println(response[i]);}}catch(UnknownHostException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}}//执行过程中,有一个参数时的构造方法,参数指定服务器地址,取默认端口10745public ClientSocketDemo(String hostname){try{//创建客户端socket,hostname参数指定服务器地址,端口号为10745 socket = new Socket(hostname,10745);in = new DataInputStream(socket.getInputStream());out = new DataOutputStream(socket.getOutputStream());String ip = String.valueOf(socket.getLocalAddress());String port = String.valueOf(socket.getLocalPort());out.writeUTF("Hello Server.This connection is from client.");out.writeUTF(ip);out.writeUTF(port);response = new String[3];for (int i = 0; i < response.length; i++){response[i] = in.readUTF();System.out.println(response[i]);}}catch(UnknownHostException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}}//执行过程中,有两个个参数时的构造方法,第一个参数hostname指定服务器地址//第一个参数serverPort指定服务器端口号public ClientSocketDemo(String hostname,String serverPort){try{socket = new Socket(hostname,Integer.parseInt(serverPort)); in = new DataInputStream(socket.getInputStream());out = new DataOutputStream(socket.getOutputStream());String ip = String.valueOf(socket.getLocalAddress());String port = String.valueOf(socket.getLocalPort());out.writeUTF("Hello Server.This connection is from client."); out.writeUTF(ip);out.writeUTF(port);response = new String[3];for (int i = 0; i < response.length; i++){response[i] = in.readUTF();System.out.println(response[i]);}}catch(UnknownHostException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}}public static void main(String[] args){String comd[] = args;if(comd.length == 0){System.out.println("Use localhost(127.0.0.1) and default port");ClientSocketDemo demo = new ClientSocketDemo();}else if(comd.length == 1){System.out.println("Use default port");ClientSocketDemo demo = new ClientSocketDemo(args[0]);}else if(comd.length == 2){System.out.println("Hostname and port are named by user");ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);}else System.out.println("ERROR");}}//////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////【ServerSocketDemo.java 服务器端Java源代码】import .*;import java.io.*;public class ServerSocketDemo{//声明ServerSocket类对象ServerSocket serverSocket;//声明并初始化服务器端监听端口号常量public static final int PORT = 10745;//声明服务器端数据输入输出流DataInputStream in;DataOutputStream out;//声明InetAddress类对象ip,用于获取服务器地址及端口号等信息InetAddress ip = null;//声明字符串数组对象request,用于存储从客户端发送来的信息String request[];public ServerSocketDemo(){request = new String[3]; //初始化字符串数组try{//获取本地服务器地址信息ip = InetAddress.getLocalHost();//以PORT为服务端口号,创建serverSocket对象以监听该端口上的连接serverSocket = new ServerSocket(PORT);//创建Socket类的对象socket,用于保存连接到服务器的客户端socket对象Socket socket = serverSocket.accept();System.out.println("This is server:"+String.valueOf(ip)+PORT); //创建服务器端数据输入输出流,用于对客户端接收或发送数据in = new DataInputStream(socket.getInputStream());out = new DataOutputStream(socket.getOutputStream());//接收客户端发送来的数据信息,并显示request[0] = in.readUTF();request[1] = in.readUTF();request[2] = in.readUTF();System.out.println("Received messages form client is:"); System.out.println(request[0]);System.out.println(request[1]);System.out.println(request[2]);//向客户端发送数据out.writeUTF("Hello client!");out.writeUTF("Your ip is:"+request[1]);out.writeUTF("Your port is:"+request[2]);}catch(IOException e){e.printStackTrace();}}public static void main(String[] args){ServerSocketDemo demo = new ServerSocketDemo();}}。

java聊天室的实现代码

java聊天室的实现代码

java聊天室的实现代码本⽂实例为⼤家分享了java实现聊天室的具体代码,供⼤家参考,具体内容如下聊天室界⾯:源码:public class ClientFrame extends Frame {private TextField textFieldContent = new TextField();private TextArea textAreaContent = new TextArea();private Socket socket = null;private OutputStream out = null;private DataOutputStream dos = null;private InputStream in = null;private DataInputStream dis = null;private boolean flag = false;/*** 学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午9:19:51 功能:启动客户端程序** @param args*/public static void main(String[] args) {new ClientFrame().init();}/*** 学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午9:20:43 功能:对窗⼝进⾏初始化 */private void init() {this.setSize(300, 300);setLocation(250, 150);setVisible(true);setTitle("WeChatRoom");// 添加控件this.add(textAreaContent);this.add(textFieldContent, BorderLayout.SOUTH);textAreaContent.setFocusable(false);pack();// 关闭事件addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.out.println("⽤户试图关闭窗⼝");disconnect();System.exit(0);}});// textFieldContent添加回车事件textFieldContent.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {onClickEnter();}});// 建⽴连接connect();new Thread(new ReciveMessage()).start();}private class ReciveMessage implements Runnable {@Overridepublic void run() {flag = true;try {while (flag) {String message = dis.readUTF();textAreaContent.append(message + "\n");}} catch (EOFException e) {flag = false;System.out.println("客户端已关闭");// e.printStackTrace();} catch (SocketException e) {flag = false;System.out.println("客户端已关闭");// e.printStackTrace();} catch (IOException e) {flag = false;System.out.println("接受消息失败");e.printStackTrace();}}}/*** 功能:当点击回车时出发的事件学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午9:49:30 */private void onClickEnter() {String message = textFieldContent.getText().trim();if (message != null && !message.equals("")) {String time = new SimpleDateFormat("h:m:s").format(new Date());textAreaContent.append(time + "\n" + message + "\n");textFieldContent.setText("");sendMessageToServer(message);}}/*** 功能:给服务器发送消息学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午10:13:48** @param message*/private void sendMessageToServer(String message) {try {dos.writeUTF(message);dos.flush();} catch (IOException e) {System.out.println("发送消息失败");e.printStackTrace();}}/*** 功能:申请socket链接学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午10:00:38*/private void connect() {try {socket = new Socket("localhost", 8888);out = socket.getOutputStream();dos = new DataOutputStream(out);in = socket.getInputStream();dis = new DataInputStream(in);} catch (UnknownHostException e) {System.out.println("申请链接失败");e.printStackTrace();} catch (IOException e) {System.out.println("申请链接失败");e.printStackTrace();}}/*** 功能:关闭流和链接学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午10:01:32*/private void disconnect() {flag = false;if (dos != null) {try {dos.close();} catch (IOException e) {System.out.println("dos关闭失败");e.printStackTrace();}}if (out != null) {try {out.close();} catch (IOException e) {System.out.println("dos关闭失败");e.printStackTrace();}}if (socket != null) {try {socket.close();} catch (IOException e) {System.out.println("socket关闭失败");e.printStackTrace();};}}}package com.chat;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.EOFException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import .BindException;import .ServerSocket;import .Socket;import .SocketException;import java.util.ArrayList;import java.util.List;public class ChatServer {private List<Client> clients = new ArrayList<>();/*** 功能:启动ChatSever 学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午10:26:41** @param args*/public static void main(String[] args) {new ChatServer().init();}/*** 功能:对chatserver初始化学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午10:27:09private void init() {System.out.println("服务器已开启");// BindExceptionServerSocket ss = null;Socket socket = null;try {ss = new ServerSocket(8888);} catch (BindException e) {System.out.println("端⼝已被占⽤");e.printStackTrace();} catch (IOException e1) {e1.printStackTrace();}try {Client client = null;while (true) {socket = ss.accept();System.out.println("客户驾到");client = new Client(socket);clients.add(client);new Thread(client).start();}} catch (IOException e) {e.printStackTrace();}}private class Client implements Runnable {private Socket socket = null;InputStream in = null;DataInputStream din = null;OutputStream out = null;DataOutputStream dos = null;boolean flag = true;public Client(Socket socket) {this.socket = socket;try {in = socket.getInputStream();din = new DataInputStream(in);} catch (IOException e) {System.out.println("接受消息失败");e.printStackTrace();}}public void run() {String message;try {while (flag) {message = din.readUTF();// System.out.println("客户说:" + message); forwordToAllClients(message);}} catch (SocketException e) {flag = false;System.out.println("客户下线");clients.remove(this);// e.printStackTrace();} catch (EOFException e) {flag = false;System.out.println("客户下线");clients.remove(this);// e.printStackTrace();} catch (IOException e) {flag = false;System.out.println("接受消息失败");clients.remove(this);e.printStackTrace();}if (din != null) {din.close();} catch (IOException e) {System.out.println("din关闭失败");e.printStackTrace();}}if (in != null) {try {in.close();} catch (IOException e) {System.out.println("din关闭失败");e.printStackTrace();}}if (socket != null) {try {socket.close();} catch (IOException e) {System.out.println("din关闭失败");e.printStackTrace();}}}/*** 功能:转发给所有客户端学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午11:11:59 ** @param message* @throws IOException*/private void forwordToAllClients(String message) throws IOException {for (Client c : clients) {if (c != this) {out = c.socket.getOutputStream();dos = new DataOutputStream(out);forwordToClient(message);}}}/*** 功能:发送给⼀个客户端学校:⼭东师范⼤学程序员:外⼒_Victor ⽇期:2016年5⽉8⽇上午11:16:12 ** @throws IOException*/private void forwordToClient(String message) throws IOException {dos.writeUTF(message);dos.flush();System.out.println("转发成功!");}}}源码下载:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Java聊天室制作人:_____杨永生_____制作时间:2012.9.26目录1本文简介 (2)2聊天室截图与说明 (2)2.1用Java编译: (2)2.2服务器登录界面 (2)2.3服务器窗口 (2)2.4客服端登录界面 (3)2.5客服端窗口 (3)3服务器端 (6)3.1MyServer()方法 (6)3.2Login()方法 (10)3.3Time()方法 (13)4客户端 (14)4.1MyClient()方法 (14)4.2Login()方法 (18)4.3Time()方法 (20)1 本文简介这是一个简单的Java聊天室,仅提供给一些刚学Java的学生做实验,本文也是仅供参考.本文代码都有注释,希望读者能读懂代码,本实验内部还有一些错误,比如只能一条一条的发信息,不能连发,希望能解决本问题的朋友能给我发信息,我的QQ号就是百度号!2 聊天室截图与说明2.1 用Java编译:本代码有七个类,放在六个java文件中,类名在下方希望读者自己观看, 2.2 服务器登录界面要先运行服务器端的程序用户名:y密码:1用户名密码可以自己设定点击确定可以登录,2秒后到服务端界面2.3 服务器窗口聊天室的IP为本机的网络虚拟IP,在任何电脑上都能用,端口应设置在1024以后, 2.4 客服端登录界面和服务器端的登录一样2.5 客服端窗口当登录上后客服端就显示已经连接了,此时服务器端的窗口如下由于本程序设计的不是很完整,具体的聊天要先从客服端开始:在客服端输入一条聊天内容后按确定,在服务器端就可以收到信息,之后客户端不能输入了,要等待服务器端来信息后才能继续输入信息.想要结束聊天,直接可以关闭窗口,也可以输入’bye’后断开聊天有兴趣的朋友可以继续完善本实验程序.3 服务器端3.1 MyServer()方法//服务器端代码import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import .ServerSocket;import .Socket;import java.text.DateFormat;import java.util.Date;import javax.swing.*;public class MyServer{ //窗体实现类protected JLabel lab10; //全体变量,做传递的一个组件String s="已经成功连接"; //初始字符串,在两个聊天窗口链接成功时输出,同时作为两个窗口传递字符的一个变量//构造方法public MyServer(){try{//异常处理tryJFrame frame=new JFrame("服务器窗口"); //设置窗体frame.setLayout(null); //让布局管理器为空,使用绝对定位Font fnt=new Font("Serief",Font.PLAIN,40);//字体设置Font fnt1=new Font("Serief",Font.PLAIN,20);//字体设置//我的用户名显示JLabel lab1=new JLabel("服务器名:",JLabel.LEFT); //标签实例化,文本左对齐lab1.setBounds(8, 10, 100, 20); //设置组件位置及大小frame.add(lab1); //添加组件JTextField text2=new JTextField(30); //单行文本输入组件text2.setBounds(150, 10, 200, 20);//设置组件位置及大小text2.setEnabled(false);//文本条不可编辑text2.setText("笑笑聊天室");//输入内容text2.setFont(fnt1);//设置字体frame.add(text2);//添加组件//服务器IP显示JLabel lab2=new JLabel("当前服务器IP:",JLabel.LEFT); //标签实例化,文本左对齐lab2.setBounds(8, 45, 100, 20);//设置组件位置及大小frame.add(lab2);//添加组件JTextField text3=new JTextField(30);//单行文本输入组件text3.setBounds(150, 45, 200, 20);//设置组件位置及大小text3.setEnabled(false); //文本不可编辑text3.setText("127.0.0.1");//输入内容text3.setFont(fnt1);//设置字体frame.add(text3); //添加组件//服务器端口显示JLabel lab3=new JLabel("当前服务器端口:",JLabel.LEFT); //标签实例化,文本左对齐lab3.setBounds(8, 80, 100, 20);//设置组件位置及大小frame.add(lab3);//添加组件JTextField text4=new JTextField(30);//单行文本输入组件text4.setBounds(150, 80, 200, 20);//设置组件位置及大小text4.setEnabled(false);//文本不可编辑text4.setText("8888");//输入内容text4.setFont(fnt1);//设置字体frame.add(text4);//添加组件//聊天记录显示JLabel lab4=new JLabel("聊天记录如下:",JLabel.LEFT); //标签实例化,文本左对齐lab4.setBounds(8, 115, 100, 20);//设置组件位置及大小frame.add(lab4);//添加组件final JTextArea text1=new JTextArea();//多行文本输入组件text1.setEnabled(false);//文本不可编辑text1.setLineWrap(true);//自动换行JScrollPane scr=new JScrollPane(text1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.H ORIZONTAL_SCROLLBAR_ALWAYS); //设置滚动条,水平和垂直滚动条始终显示scr.setBounds(8, 150, 450, 350);//设置组件位置及大小frame.add(scr);//添加组件//聊天输入窗口及确定JLabel lab5=new JLabel("请输入聊天内容:",JLabel.LEFT); //标签实例化,文本左对齐lab5.setBounds(8, 500, 100, 20);//设置组件位置及大小frame.add(lab5);//添加组件final JTextArea text5=new JTextArea();//多行文本输入组件text5.setLineWrap(true);//自动换行JScrollPane scr2=new JScrollPane(text5,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.H ORIZONTAL_SCROLLBAR_ALWAYS);//设置滚动条,水平和垂直滚动条始终显示scr2.setBounds(150, 500, 300, 50);//设置组件位置及大小frame.add(scr2);//添加组件final JButton but=new JButton("确定");//设置确定按钮but.setFont(fnt);//添加字体设置but.setBounds(480, 500, 200, 50);//设置组件位置及大小but.addActionListener(new ActionListener(){ //采用内部匿名类public void actionPerformed(ActionEvent e){if(e.getSource()==but){ //判断触发器源是否是提交按钮text1.append("笑笑: "+lab10.getText()+"\n ");//在聊天记录上添加文本text1.append(text5.getText()+"\n"); //将输入的聊天内容输出在聊天记录上s=text5.getText(); //得到聊天内容text5.setText(""); // 将聊天窗口内容设置为空}}}) ;frame.add(but);//添加组件//当前时间显示JLabel lab7=new JLabel("时间显示:",JLabel.LEFT);//标签实例化,文本左对齐lab7.setBounds(450, 20, 100, 20);//设置组件位置及大小frame.add(lab7);//添加组件DateFormat df=DateFormat.getDateTimeInstance();//取得系统时间String df2= df.format(new Date()); //将时间转换成字符串JLabel lab8=new JLabel(df2,JLabel.LEFT);//标签实例化,文本左对齐lab8.setBounds(520, 20, 130, 20);//设置组件位置及大小frame.add(lab8);//添加组件lab10=lab8; //传递时间显示,以便能在聊天记录上显示记录时间new Time(lab8); //使时间动态显示//用户列表显示JLabel lab6=new JLabel("用户列表:",JLabel.LEFT);//标签实例化,文本左对齐lab6.setBounds(500, 40, 100, 20);//设置组件位置及大小frame.add(lab6);//添加组件JTextArea text6=new JTextArea();//标签实例化,文本左对齐text6.setEnabled(false);//文本不可编辑text6.setLineWrap(true);//自动换行JScrollPane scr3=new JScrollPane(text6,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.H ORIZONTAL_SCROLLBAR_ALWAYS);//设置滚动条,水平和垂直滚动条始终显示scr3.setBounds(460, 70, 220, 420);//设置组件位置及大小frame.add(scr3);//添加组件//窗口的属性frame.setSize(700,600);//窗口大小frame.getContentPane().setBackground(Color.pink);//窗口的背景颜色frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时关闭程序frame.setLocation(100,50);//在电脑桌面上出现的位置frame.setVisible(true);//显示窗口//连个窗口连接//建立Server Socket并等待连接请求ServerSocket server =new ServerSocket(8889);Socket socket=server.accept();//连接建立,通过Socket获取连接上的输入/输出流BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));final PrintWriter out =new PrintWriter(socket.getOutputStream());//先读取Client发送的数据,然后从标准输入读取数据发送给Client当接收到bye时关闭连接String s1="",s2=""; //标志字符串,作为传递字符串使用while(!(s1=in.readLine()).equals("bye")){ //得到其他窗口传递的字符串,并判断是否结束text6.setText("可可在线"); //当连接成功是在用户列表中输出用户名字if(!s1.equals("")){ //如果传递的字符串不为空text1.append("可可: "+lab10.getText()+"\n ");//在聊天记录上添加文本text1.append(s1+"\n"); //将输入的聊天内容输出在聊天记录上}s2=s;//将在聊天窗口中得到的字符串传递给输出字符串for(;s2.equals("")||s2.equals(null);s2=s){//当传递的字符串为空时等待用户输入聊天内容}s="";//将在聊天窗口中得到的字符串设为空if(!s2.equals("")&&!s2.equals(null)){// s2不为空时做out.println(s2); //向其他窗口输出字符串}out.flush();//输出聊天内容}//关闭连接in.close();out.close();socket.close();server.close();}catch(Exception e){}}//main函数public static void main(String args[]){new Login();//登录实现}}3.2 Login()方法import java.awt.event.WindowAdapter ;import java.awt.event.ActionListener ;import java.awt.event.WindowEvent ;import java.awt.event.ActionEvent ;import java.awt.Color ;import java.awt.Font ;import javax.swing.JFrame ;import javax.swing.JButton ;import javax.swing.JLabel ;import javax.swing.JTextField ;import javax.swing.JPasswordField ;//用户名和密码设置class LoginCheck{//设置登录密码private String name ;//用户名private String password ;//密码//构造方法public LoginCheck(String name,String password){ = name ;//传递用户名this.password = password ;//传递密码}//验证用户名和密码public boolean validate(){//验证方法if("y".equals(name)&&"1".equals(password)){ //判断用户名和密码是否正确return true ;//返回true}else{return false ;//返回false}}};//登录窗口class Login{//登录类名boolean f=false;//按登录时设置的一个标志private JFrame frame = new JFrame("Welcome To MLDN") ; //设置窗体private JButton submit = new JButton("登陆");//设置登录按钮private JButton reset = new JButton("重置");//设置重置按钮private JLabel nameLab = new JLabel("服务器:") ;//标签实例化private JLabel passLab = new JLabel("密码:") ;//标签实例化private JLabel infoLab = new JLabel("服务器登陆系统") ;//标签实例化private JTextField nameText = new JTextField(10) ;//单行文本输入条private JPasswordField passText = new JPasswordField() ;//单行密码文本输入条public Login(){//登录窗口构造方法Font fnt = new Font("Serief",Font.ITALIC + Font.BOLD,12) ;//设置字体infoLab.setFont(fnt) ; // 设置标签的显示文字submit.addActionListener(new ActionListener(){ //采用内部匿名类public void actionPerformed(ActionEvent e){if(e.getSource()==submit){ //判断触发器源是否是提交按钮String tname = nameText.getText() ; //得到输入的用户名String tpass = new String(passText.getPassword()) ;//得到输入的密码,此时通过getPassageword()方法返回的是字符数组LoginCheck log = new LoginCheck(tname,tpass) ;//实例化LoginCheck对象,传入输入的用户名和密码if(log.validate()){//对用户名和密码进行验证try{ //线程异常处理tryThread.sleep(2000); //2秒后打开聊天窗口f=true; //登录成功后的表示项为trueframe.dispose(); //关闭本窗口}catch(Exception ee){//异常获取}}else{infoLab.setText("登陆失败,错误的用户名或密码!") ;//登录失败}}}}) ;reset.addActionListener(new ActionListener(){ //采用内部匿名类public void actionPerformed(ActionEvent e){if(e.getSource()==reset){ //判断触发器源是否是提交按钮nameText.setText("") ;//设置文本框中的内容passText.setText("") ;//设置文本框中的内容infoLab.setText("服务器登陆系统") ;//恢复标签显示}}}) ;frame.addWindowListener(new WindowAdapter(){//加入窗口监听public void windowClosing(WindowEvent e){}}) ; // 加入事件frame.setLayout(null) ;//使用绝对定位nameLab.setBounds(5,5,60,20) ;//设置标签的位置及大小passLab.setBounds(5,30,60,20) ;//设置标签的位置及大小infoLab.setBounds(5,65,220,30) ;//设置标签的位置及大小nameText.setBounds(65,5,100,20) ;//设置文本域的位置及大小passText.setBounds(65,30,100,20) ;//设置密码域的位置及大小submit.setBounds(165,5,60,20) ;//设置按钮的位置及大小reset.setBounds(165,30,60,20) ;//设置按钮的位置及大小frame.add(nameLab) ;//向窗体加入标签frame.add(passLab) ;//向窗体加入标签frame.add(infoLab) ;//向窗体加入标签frame.add(nameText) ;//向窗体加入文本框frame.add(passText) ;//向窗体加入密码框frame.add(submit) ;//向窗体加入按钮frame.add(reset) ;//向窗体加入按钮frame.setSize(280,130) ;//设置窗体大小frame.getContentPane().setBackground(Color.green) ;//设置窗体的背景颜色frame.setLocation(300,200) ;//设置窗体在电脑桌面上的位置frame.setVisible(true) ;//显示窗口while(f==false){ //当登录失败时,一直循环运行,}new MyServer();//显示窗体页面}}3.3 Time()方法import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.JLabel;import javax.swing.Timer;//时间类public class Time {public Time(JLabel time){ //构造方法this.setTimer(time); //设置时间}public void setTimer(JLabel time){ //设置时间方法final JLabel varTime = time; //传递组件Timer timeAction = new Timer(1000, new ActionListener() { //时间监听public void actionPerformed(ActionEvent e) {long timemillis = System.currentTimeMillis(); //得到系统时间SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //转换日期显示格式varTime.setText(df.format(new Date(timemillis))); //输出得到的时间}});timeAction.start(); //开启线程}}4 客户端4.1 MyClient()方法import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import .Socket;import java.text.DateFormat;import java.util.Date;import javax.swing.*;public class MyClient{protected JLabel lab10;//全体变量,做传递的一个组件String s="连接成功";//初始字符串,在两个聊天窗口链接成功时输出,同时作为两个窗口传递字符的一个变量//构造方法public MyClient(){JFrame frame=new JFrame("用户端窗口"); //设置窗体frame.setLayout(null); //让布局管理器为空,使用绝对定位Font fnt=new Font("Serief",Font.PLAIN,40);//字体设置Font fnt1=new Font("Serief",Font.PLAIN,20);//字体设置//我的用户名显示JLabel lab1=new JLabel("服务器名:",JLabel.LEFT); //标签实例化,文本左对齐lab1.setBounds(8, 10, 100, 20); //设置组件位置及大小frame.add(lab1); //添加组件JTextField text2=new JTextField(30); //单行文本输入组件text2.setBounds(150, 10, 200, 20);//设置组件位置及大小text2.setEnabled(false);//文本条不可编辑text2.setText("可可聊天室");//输入内容text2.setFont(fnt1);//设置字体frame.add(text2);//添加组件//服务器IP显示JLabel lab2=new JLabel("当前服务器IP:",JLabel.LEFT); //标签实例化,文本左对齐lab2.setBounds(8, 45, 100, 20);//设置组件位置及大小frame.add(lab2);//添加组件JTextField text3=new JTextField(30);//单行文本输入组件text3.setBounds(150, 45, 200, 20);//设置组件位置及大小text3.setEnabled(false); //文本不可编辑text3.setText("127.0.0.1");//输入内容text3.setFont(fnt1);//设置字体frame.add(text3); //添加组件//服务器端口显示JLabel lab3=new JLabel("当前服务器端口:",JLabel.LEFT); //标签实例化,文本左对齐lab3.setBounds(8, 80, 100, 20);//设置组件位置及大小frame.add(lab3);//添加组件JTextField text4=new JTextField(30);//单行文本输入组件text4.setBounds(150, 80, 200, 20);//设置组件位置及大小text4.setEnabled(false);//文本不可编辑text4.setText("8888");//输入内容text4.setFont(fnt1);//设置字体frame.add(text4);//添加组件//聊天记录显示JLabel lab4=new JLabel("聊天记录如下:",JLabel.LEFT); //标签实例化,文本左对齐lab4.setBounds(8, 115, 100, 20);//设置组件位置及大小frame.add(lab4);//添加组件final JTextArea text1=new JTextArea();//多行文本输入组件text1.setEnabled(false);//文本不可编辑text1.setLineWrap(true);//自动换行JScrollPane scr=new JScrollPane(text1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.H ORIZONTAL_SCROLLBAR_ALWAYS); //设置滚动条,水平和垂直滚动条始终显示scr.setBounds(8, 150, 450, 350);//设置组件位置及大小frame.add(scr);//添加组件//聊天输入窗口及确定JLabel lab5=new JLabel("请输入聊天内容:",JLabel.LEFT); //标签实例化,文本左对齐lab5.setBounds(8, 500, 100, 20);//设置组件位置及大小frame.add(lab5);//添加组件final JTextArea text5=new JTextArea();//多行文本输入组件text5.setLineWrap(true);//自动换行JScrollPane scr2=new JScrollPane(text5,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.H ORIZONTAL_SCROLLBAR_ALWAYS);//设置滚动条,水平和垂直滚动条始终显示scr2.setBounds(150, 500, 300, 50);//设置组件位置及大小frame.add(scr2);//添加组件final JButton but=new JButton("确定");//设置确定按钮but.setFont(fnt);//添加字体设置but.setBounds(480, 500, 200, 50);//设置组件位置及大小but.addActionListener(new ActionListener(){ //采用内部匿名类public void actionPerformed(ActionEvent e){if(e.getSource()==but){ //判断触发器源是否是提交按钮text1.append("可可: "+lab10.getText()+"\n ");//在聊天记录上添加文本text1.append(text5.getText()+"\n");//将输入的聊天内容输出在聊天记录上s=text5.getText(); //得到聊天内容text5.setText(""); // 将聊天窗口内容设置为空}}}) ;frame.add(but);//添加组件//当前时间显示JLabel lab7=new JLabel("时间显示:",JLabel.LEFT);//标签实例化,文本左对齐lab7.setBounds(450, 20, 100, 20);//设置组件位置及大小frame.add(lab7);//添加组件DateFormat df=DateFormat.getDateTimeInstance();//取得系统时间String df2= df.format(new Date()); //将时间转换成字符串JLabel lab8=new JLabel(df2,JLabel.LEFT);//标签实例化,文本左对齐lab8.setBounds(520, 20, 130, 20);//设置组件位置及大小frame.add(lab8);//添加组件lab10=lab8; //传递时间显示,以便能在聊天记录上显示记录时间new Time(lab8); //使时间动态显示//用户列表显示JLabel lab6=new JLabel("用户列表:",JLabel.LEFT);//标签实例化,文本左对齐lab6.setBounds(500, 40, 100, 20);//设置组件位置及大小frame.add(lab6);//添加组件JTextArea text6=new JTextArea();//标签实例化,文本左对齐text6.setEnabled(false);//文本不可编辑text6.setLineWrap(true);//自动换行JScrollPane scr3=new JScrollPane(text6,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.H ORIZONTAL_SCROLLBAR_ALWAYS);//设置滚动条,水平和垂直滚动条始终显示scr3.setBounds(460, 70, 220, 420);//设置组件位置及大小frame.add(scr3);//添加组件//窗口的属性frame.setSize(700,600);//窗口大小frame.getContentPane().setBackground(Color.pink);//窗口的背景颜色frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时关闭程序frame.setLocation(10,10);//在电脑桌面上出现的位置frame.setVisible(true);//显示窗口try{ //try异常处理Socket socket=new Socket("127.0.0.1",8889); //发出连接请求//建立连接,通过Socket获得连接上的输入/输出流PrintWriter out =new PrintWriter(socket.getOutputStream());BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));//从标准输入中读取一行,发送Server端,当用户输入bye时结束连接do{while(s.equals("")||s.equals(null)){//当传递的字符串为空时等待用户输入聊天内容}if(!s.equals("")&&!s.equals(null)){//s不为空时做out.println(s); //向其他窗口输出字符串s=""; //将在聊天窗口中得到的字符串设为空}out.flush();//输出聊天内容if(!s.equals("bye")){ //判断聊天是否结束String s3; //得到其他窗口传来的字符串while( (s3=in.readLine()).equals("\n")&&s3.equals(null)&&s3.equals("")){//判断s3是否为空,为空时等待}text6.setText("笑笑在线"); //当连接成功是在用户列表中输出用户名字if(!s3.equals("\n")&&!s3.equals(null)&&!s3.equals("")){//s3不为空时做text1.append("笑笑: "+lab10.getText()+"\n ");//在聊天记录上添加文本text1.append(s3+"\n"); //将输入的聊天内容输出在聊天记录上}}}while(!s.equals("bye"));//判断是否结束//关闭连接out.close();in.close();socket.close();}catch(Exception e){}}//main函数public static void main(String args[]){new Login();//登录实现}}4.2 Login()方法import java.awt.event.WindowAdapter ;import java.awt.event.ActionListener ;import java.awt.event.WindowEvent ;import java.awt.event.ActionEvent ;import java.awt.Color ;import java.awt.Font ;import javax.swing.JFrame ;import javax.swing.JButton ;import javax.swing.JLabel ;import javax.swing.JTextField ;import javax.swing.JPasswordField ;//用户名和密码设置class LoginCheck{//设置登录密码private String name ;//用户名private String password ;//密码//构造方法public LoginCheck(String name,String password){ = name ;//传递用户名this.password = password ;//传递密码}//验证用户名和密码public boolean validate(){//验证方法if("y".equals(name)&&"1".equals(password)){ //判断用户名和密码是否正确return true ;//返回true}else{return false ;//返回false}}};//登录窗口class Login{//登录类名boolean f=false;//按登录时设置的一个标志private JFrame frame = new JFrame("Welcome To MLDN") ; //设置窗体private JButton submit = new JButton("登陆");//设置登录按钮private JButton reset = new JButton("重置");//设置重置按钮private JLabel nameLab = new JLabel("用户名:") ;//标签实例化private JLabel passLab = new JLabel("密码:") ;//标签实例化private JLabel infoLab = new JLabel("用户登陆系统") ;//标签实例化private JTextField nameText = new JTextField(10) ;//单行文本输入条private JPasswordField passText = new JPasswordField() ;//单行密码文本输入条public Login(){//登录窗口构造方法Font fnt = new Font("Serief",Font.ITALIC + Font.BOLD,12) ;//设置字体infoLab.setFont(fnt) ; // 设置标签的显示文字submit.addActionListener(new ActionListener(){ //采用内部匿名类public void actionPerformed(ActionEvent e){if(e.getSource()==submit){ //判断触发器源是否是提交按钮String tname = nameText.getText() ; //得到输入的用户名String tpass = new String(passText.getPassword()) ;//得到输入的密码,此时通过getPassageword()方法返回的是字符数组LoginCheck log = new LoginCheck(tname,tpass) ;//实例化LoginCheck对象,传入输入的用户名和密码if(log.validate()){//对用户名和密码进行验证try{Thread.sleep(2000); //2秒后打开聊天窗口f=true; //登录成功后的表示项为trueframe.dispose(); //关闭本窗口}catch(Exception ee){//异常获取}}else{infoLab.setText("登陆失败,错误的用户名或密码!") ;//登录失败}}}}) ;reset.addActionListener(new ActionListener(){ //采用内部匿名类public void actionPerformed(ActionEvent e){if(e.getSource()==reset){ //判断触发器源是否是提交按钮nameText.setText("") ;//设置文本框中的内容passText.setText("") ;//设置文本框中的内容infoLab.setText("用户登陆系统") ;//恢复标签显示}}}) ;frame.addWindowListener(new WindowAdapter(){//加入窗口监听public void windowClosing(WindowEvent e){}}) ; // 加入事件frame.setLayout(null) ;//使用绝对定位nameLab.setBounds(5,5,60,20) ;//设置标签的位置及大小passLab.setBounds(5,30,60,20) ;//设置标签的位置及大小infoLab.setBounds(5,65,220,30) ;//设置标签的位置及大小nameText.setBounds(65,5,100,20) ;//设置文本域的位置及大小passText.setBounds(65,30,100,20) ;//设置密码域的位置及大小submit.setBounds(165,5,60,20) ;//设置按钮的位置及大小reset.setBounds(165,30,60,20) ;//设置按钮的位置及大小frame.add(nameLab) ;//向窗体加入标签frame.add(passLab) ;//向窗体加入标签frame.add(infoLab) ;//向窗体加入标签frame.add(nameText) ;//向窗体加入文本框frame.add(passText) ;//向窗体加入密码框frame.add(submit) ;//向窗体加入按钮frame.add(reset) ;//向窗体加入按钮frame.setSize(280,130) ;//设置窗体大小frame.getContentPane().setBackground(Color.green) ;//设置窗体的背景颜色frame.setLocation(300,200) ;//设置窗体在电脑桌面上的位置frame.setVisible(true) ;//显示窗口while(f==false){//当登录失败时,一直循环运行,}new MyClient();//显示窗体页面}};4.3 Time()方法import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.JLabel;import javax.swing.Timer;//时间类public class Time {public Time(JLabel time){//构造方法this.setTimer(time);//设置时间}public void setTimer(JLabel time){ //设置时间方法final JLabel varTime = time; //传递组件Timer timeAction = new Timer(1000, new ActionListener() { //时间监听public void actionPerformed(ActionEvent e) {long timemillis = System.currentTimeMillis(); //得到系统时间java聊天室SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //转换日期显示格式varTime.setText(df.format(new Date(timemillis))); //输出得到的时间}});timeAction.start(); //开启线程}}共21页第21页。

相关文档
最新文档