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)){
  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页。

相关文档
最新文档