Java聊天程序实验报告
- 格式:doc
- 大小:85.00 KB
- 文档页数:8
网络聊天程序实验报告组长:xxx PB09210xxx其他组员:无实验内容用面向对象程序设计方法编写一个网络聊天程序。
程序的功能是允许处在网络上不同结点的多个用户进行文字聊天。
最基本的要求是实现一对一的聊天,即最多只允许两个人在线。
也可以实现多人同时聊天,即在线的任何一个用户输入的文字,其他的人都能立即收到。
建议采用 Socket通讯方式。
实验实现(一)概要设计:GAGA聊天程序实现结构图:注: 图中粗箭头表示信息传递图解:在客户端着一端:每一个客户端登录时候,先向服务器发送一个登录名的信息,向服务器注册这个客户端,然后进入群聊窗口,可以直接在群聊窗口中发送群聊的信息,也可以点击在线用户,打开私聊窗口,向相应用户私聊。
群聊,私聊的消息发送给服务器,服务器再把这些消息广播给所有客户端,每个客户端对接受的消息进行识别:要是群聊消息则放到群聊窗口里面;要是私聊信息,检查是不是给自己的私聊信息,要是给自己的,显示到相应私聊窗口上,要是没有相应私聊窗口则创建那个私聊窗口 ;要是不是自己的私聊消息则无视这个消息在服务器这一端:每一个客户端与服务器建立连接时候,就为它建立一个CreatServerThread的线程类,用来专门处理这个客户端。
服务器每当接收到消息后就使用Broadcast线程类进行广播,直到消息列表里面的消息发送完为止。
Broadcast是通过查找CreatServerThread线程类的数组,找到每个CreatServerThread线程类,也就找到每个客户端,再逐个发送消息(二)详细设计:实验实现代码结构客户端:(每种颜色代表一个类)package Client;// 主类message_frame,用来创建message_frame_to类public class message_frame{public static void main(String args[]){ // 主函数,创建message_frame_to类,调用其构造函数message_frame_to m=new message_frame_to() ;}}// 主类message_frame结束//类message_frame_to,用于创建客户端群聊窗口,与服务器连接,接发消息class message_frame_to extends KeyAdapter implements ActionListener{public message_frame_to(){ //构造函数,调用其他函数Frame() ; // 建立主框架Text() ; // 建立文本域Label() ; // 建立标签域Button() ; // 建立按钮域online_users() ; // 建立在线用户列表Dlog D=new Dlog() ; // 建立登陆界面Client() ; // 连接服务器函数}// 建立主框架函数public static void Frame(){ }// 文本域函数public static void Text(){ }// 标签域函数public static void Label(){ }// 按钮函数public void Button(){ }// 按钮监听函数public void actionPerformed(ActionEvent e){ }// 输入框键盘监听函数,支持CTRL+ENTER快捷键发送消息public void keyReleased(KeyEvent e){ }// 在线列表函数public void online_users(){ }//服务器建立连接与接收数据函数public int Client(){ }// 群聊信息发送函数public void send(){ }// 延迟函数,用来解决需要延迟执行问题public static void deley(int ms){ }// 抖屏函数public void shake(){ }}//类message_frame_to结束//私聊窗口类(线程派生类),每点击一个用户进行私聊时候,就创建一个对应的私聊窗口class frame extends Thread implements ActionListener{// 构造函数public frame(String s){send_name = s;start() ;}// 构造函数结束// run函数,用来构造私聊窗口public void run(){ }// 私聊窗口按钮监听执行器函数public void actionPerformed(ActionEvent e){ }//私聊消息发送函数public void send_one(){ }// 私聊窗口信息显示函数public void write(String inn){ }} // 私聊窗口类结束// 登录界面类,用来构造登录界面class Dlog extends Frame implements ActionListener {// 构造函数,创建登录窗口界面public Dlog(){ }// 登录窗口按钮监听执行器函数public void actionPerformed(ActionEvent e){ }} // 登录界面类结束// 音乐播放类,可以播放wav格式音乐class PlayWav{// 构造函数public PlayWav(String soun){ }// 播放函数public void play(){ }} //音乐播放类结束服务器:(Server为最大类,内部包含两个子类以用不同颜色表明)package Server;// 主类Server,是整个服务器的类public class Server extends ServerSocket implements ActionListener{//主函数public static void main(String[] args) throws IOException{new Server(); // 调用Server构造函数}// Sever函数,用来监听客户端连接public Server() throws IOException{ }// 服务器的界面设计window函数public void window(){ }//服务器GUI上按钮监听执行器函数public void actionPerformed(ActionEvent e){ }// 广播类(线程派生类),用来广播消息class Broadcast extends Thread{public Broadcast(){start();}// run函数,广播消息public void run(){ }}// 广播类结束// 客户端线程类,每个对应一个客户端class CreateServerThread extends Thread{// 构造函数public CreateServerThread(Socket s) throws IOException{ }// 负责接收客户端发来的消息public void run(){ }public void sendMessage(String msg){ //发送消息函数,保证发送给这个线程对应的客户端}}//线程类CreateServerThread结束} // 主类Server结束程序运行与使用说明(1)打开服务器运行Server.java,输入密码0911001,按下start按钮,文本域会出现红色的"The Server is working"字符串,表示服务器已经开始工作,要是密码输入不正确会提示"The password is wrong",重新输入正确的密码才能打开服务器,具体截图如下:(2)登入客户端运行message_frame.java,首先会跳出登录界面,输入用户名,点击sure 按钮登录:登录之后就会进入主聊天窗口,它可以支持群聊,可以看到主窗口分为:输入框Input Area ,信息框Message Area ,当前客户端用户名User , 在线用户名列表Online User ,发送按钮Send ,信息框清屏按钮Clear ,抖屏按钮Shake群聊:在输入框中输入“你们好,我是卡卡”,按CTRL+ENTER键直接发送(也可以按Send按钮发送)继续群聊:私聊:比如现在“卡卡”找“劳尔”私聊,可以直接点击主窗口在线列表里面的“劳尔”的名字,会弹出私聊窗口在私聊窗口输入信息,点击发送即可和“劳尔”私聊,此时劳尔也会跳出一个对“卡卡”的私聊窗口“劳尔”也可以对“卡卡”进行私聊然后在用户退出时候会有在线列表更新,例如“罗比尼奥”退出:注:在用户登入,退出时候都会有提示音提醒在线的所有用户,在用户有消息到来时候会有消息提示音软件特色:GAGA聊天软件,支持群聊,私聊;支持CTRL+ENTER快捷键发送(群聊);支持清屏,抖屏功能;界面清新;服务器管理便捷;使用方便等许多优点实验总结:本次的上机作业,收获颇大,以前对面向对象语言只是只懂语法,没有接受太多的编程训练,这个实验代码量较大,很好的训练的面向对象编程方式的能力,也自己摸索了很多过去没有去看得东西,比如Java的音乐播放,socket聊天这些之前不太了解的东西另外在GUI设计上面也是花了很多功夫,界面布局,各种功能器件的使用诸如此类的东西,总之,通过这次实验学习了很多新东西,也锻炼了很多老知识代码:/* 客户端程序:message_frame.java* 创建者:xxx PB09210xxx* 创建时间:2011年11月26日* 联系方式:xxx* 版本信息:version 2.0* */package Client;import java.awt.*;import javax.swing.ImageIcon;import java.awt.event.*;import javax.swing.*;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;import .*;import java.io.*;import java.util.*;import javax.sound.sampled.AudioFormat;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.DataLine;import javax.sound.sampled.SourceDataLine;import java.io.File;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;// 主类message_framepublic class message_frame{public static void main(String args[]){ // 主函数,创建message_frame_to类,调用其构造函数message_frame_to m=new message_frame_to() ;}}// 主类message_frame结束//*************************************************************************************************************************************************************************** ************//************************************************************** 类message_frame_to,用于创建客户端窗口,与服务器连接,接发消息********************************************class message_frame_to extends KeyAdapter implements ActionListener{static JFrame f=new JFrame("GAGA 2.0") ;static ImageIcon icon=new ImageIcon("C:\\scan5.jpg") ; // 聊天窗口皮肤背景static public JLabel panel = new JLabel(icon) ;public static JTextArea text_input=new JTextArea() ;public static TextArea text_message= new TextArea() ;public static Label label_4= new Label("User : ") ;Button b= new Button("Send") ;Button bc=new Button("Clear") ;Button bl=new Button("Shake") ;public static DefaultListModel listModel = new DefaultListModel();public static JList User_List= new JList(listModel); // 显示用户列表,支持私聊public static String UserName= new String(" ") ; // 当前客户端登陆账户public static Socket socket;public static BufferedReader in;public static PrintWriter out;public static ArrayList<frame> frame_Threader = new ArrayList<frame>(); // 私聊窗口列表public static Calendar now ;// 构造函数,调用其他所有函数public message_frame_to(){Frame() ; // 建立主框架Text() ; // 建立文本域Label() ; // 建立标签域Button() ; // 建立按钮域online_users() ; // 建立在线用户列表Dlog D=new Dlog() ; // 建立登陆界面Client() ; // 连接服务器函数}//构造函数结束// 建立主框架函数public static void Frame(){f.setLayout(null) ;f.setBounds(300,200,600,500) ;.f.setBackground(Color.gray) ;f.setResizable(false) ;f.setVisible(false) ;panel.setBounds(0, 0, 600, 500) ;f.add(panel) ;f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e) // 当点击关闭按钮时候,退出客户端{out.println("#");System.exit(0);}}) ;} // 主框架函数结束// 文本域函数public static void Text(){text_input.setBounds(10,400,400,100) ;text_input.setBackground(Color.white) ;. text_input.setVisible(true) ;text_input.setFont(new Font("宋体",Font.BOLD,22));text_input.setForeground(Color.blue);text_message.setBounds(10,70,400,300) ;text_message.setBackground(Color.white) ;text_message.setVisible(true) ;text_message.setFont(new Font("宋体",Font.BOLD,20));text_message.setForeground(Color.blue);text_message.setEditable(false) ;text_message.selectAll() ;panel.add(text_input) ;panel.add(text_message) ;} // 文本域函数结束// 标签域函数public static void Label(){Label label_1= new Label("Input Area") ;Label label_2= new Label("Message Area") ;Label label_3= new Label("Online User") ;label_1.setBounds(10, 370, 360, 30) ;label_1.setBackground(Color.gray) ;label_1.setVisible(true) ;label_1.setFont(new Font("黑体",Font.BOLD , 20)) ; label_1.setForeground(Color.black) ;label_2.setBounds(10, 40, 400, 30) ;label_2.setBackground(Color.gray) ;label_2.setVisible(true) ;label_2.setFont(new Font("黑体",Font.BOLD , 16)) ; label_2.setForeground(Color.black) ;label_3.setBounds(450, 85, 120, 30);label_3.setBackground(Color.gray) ;label_3.setVisible(true) ;label_3.setFont(new Font("黑体",Font.BOLD , 16)) ; label_3.setForeground(Color.black) ;label_4.setBounds(450, 40, 120, 30);label_4.setBackground(Color.gray) ;label_4.setVisible(true) ;label_4.setFont(new Font("黑体",Font.BOLD , 12)) ; label_4.setForeground(Color.black) ;panel.add(label_1) ;panel.add(label_2) ;panel.add(label_3) ;panel.add(label_4) ;}//标签域函数结束// 按钮函数public void Button(){b.setBounds(450, 440,100, 30) ;b.setBackground(Color.LIGHT_GRAY) ;b.setVisible(true) ;b.setFont(new Font("隶书",Font.BOLD , 20)) ;b.setForeground(Color.black);panel.add(b) ;b.addActionListener(this) ;bc.setBounds(450, 400,100, 30) ;bc.setBackground(Color.LIGHT_GRAY) ;bc.setVisible(true) ;bc.setFont(new Font("隶书",Font.BOLD , 20)) ;bc.setForeground(Color.black);panel.add(bc) ;bc.addActionListener(this) ;bl.setBounds(370, 370, 40, 30) ;bl.setBackground(Color.LIGHT_GRAY) ;bl.setVisible(true) ;bl.setFont(new Font("隶书",Font.BOLD , 10)) ;bl.setForeground(Color.black);panel.add(bl) ;bl.addActionListener(this) ;text_input.addKeyListener(this);} // 按钮函数结束// 按钮监听函数public void actionPerformed(ActionEvent e){if(e.getSource()==b){send();text_input.setText("") ;}if(e.getSource()==bc)text_message.setText("") ;if(e.getSource()==bl)shake() ;} // 按钮监听函数// 输入框键盘监听函数,支持CTRL+ENTER快捷键发送消息public void keyReleased(KeyEvent e){if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isControlDown()){send();text_input.setText("") ;}} // 输入框键盘监听函数结束// 在线列表函数public void online_users(){User_List.setBounds(450,120,100,200) ;User_List.setBackground(Color.white) ;User_List.setVisible(true) ;panel.add(User_List) ;User_List.addListSelectionListener(new ListSelectionListener(){ // 监听在线列表,用户点击列表上一个用户时候,跳出窗口,进行私聊public void valueChanged(ListSelectionEvent e){String s = User_List.getSelectedValue().toString() ;new frame(s) ; // 建立私聊窗口}});} // 在线列表函数结束//服务器建立连接与接收数据函数public int Client(){try{socket = new Socket("127.0.0.1", 10000); // 与服务器建立连接in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(),true);String inn ;while(true) // 一直保持监听服务器是否发送消息过来{if(!socket.isConnected()) // 检查是否与服务器断开{text_message.setText("服务器已经断开") ;break ;}inn=in.readLine() ; // 读取服务器发送过来的消息String old = message_frame_to.text_message.getText() ;if(inn.charAt(0)=='!') // “!“表现当前有用户登录或者下线,准备更新在线列表{message_frame_to.listModel.removeAllElements() ;PlayWav login_music= new PlayWav("C:\\yue1.wav") ; // 用户上下线提示音乐login_music.play() ;continue ;}if(inn.charAt(0)=='@') // ”@“表示当前接收到的是在线列表,更新在线列表{message_frame_to.listModel.addElement(inn) ;continue ;}if(inn.charAt(0)=='%') // ”%“表示当前接收的信息是私聊信息,要不是发给自己的信息则无视{if(!inn.substring(1).equals("@"+UserName)) // 检查是否是发给自己的私聊信息{inn = in.readLine();inn = in.readLine();continue ;}inn = in.readLine();String name = inn ;if(name.equals("@"+UserName)) // 检查是不是自己发送的私聊信息{inn=in.readLine() ;continue ;}int j = 0 ;if(frame_Threader.isEmpty()) // 检查是否有私聊窗口,没有则新建{String s = name ;new frame(s) ;deley(10000) ;}else{ // 在存在私聊窗口情形下,检测私聊窗口是否匹配System.out.println(frame_Threader.get(j).send_name);while(j < frame_Threader.size()&&!frame_Threader.get(j).send_name.equals(name)){j++;}if(j==frame_Threader.size()) // 不匹配,新建私聊窗口{String s = name ;new frame(s) ;deley(10000) ;}}// 将接收的信息显示到私聊窗口上inn=in.readLine() ;frame fram = frame_Threader.get(j) ;fram.write(inn.substring(1)) ;PlayWav msg_music= new PlayWav("C:\\yue2.wav") ; // 消息提示声音msg_music.play() ;continue ;}// 以上条件都不满足就是群聊消息,将接收的消息显示到群聊窗口上now = Calendar.getInstance();String str = now.getTime().toString() ;message_frame_to.text_message.setText(old+str+""+"\n"+inn.substring(1)+"\n") ;PlayWav msg_music= new PlayWav("C:\\yue2.wav") ; // 消息提示声音msg_music.play() ;} // while循环结束}catch (IOException e){}return 1 ;}//服务器建立连接与接收数据函数结束// 群聊信息发送函数public void send(){if(!socket.isConnected()){text_message.setText("服务器已经断开") ;return ;}String line = message_frame_to.text_input.getText();out.println("&"+UserName+":"+" "+line);}// 群聊信息发送函数结束// 延迟函数,用来解决需要延迟执行问题public static void deley(int ms){int killtime ;for(int i = 0 ; i < 10000 ; i++)for(int j = 0 ; j < ms ; j++){killtime = 0;killtime++;}} // 延迟函数结束// 抖屏函数public void shake(){f.setBounds(260, 160, 600, 500) ;deley(10000) ;f.setBounds(260, 240, 600, 500) ;deley(10000) ;f.setBounds(340, 240, 600, 500) ;deley(10000) ;f.setBounds(340, 240, 600, 500) ;deley(10000) ;f.setBounds(300, 200, 600, 500) ;} // 抖屏函数结束}// 类message_frame_to结束//************************************************************************************** ************************************************************************************** *******//************************************************************* 私聊窗口类(线程派生类),每点击一个用户进行私聊时候,就创建一个对应的私聊窗口****************************class frame extends Thread implements ActionListener{static ImageIcon icon=new ImageIcon("C:\\scan5.jpg") ;public static JLabel panel = new JLabel(icon) ;public static JFrame f = new JFrame() ;public static JTextArea text_input= new JTextArea() ;public static TextArea text_message= new TextArea() ;Button b= new Button("Send") ;public static String UserName= new String(" ") ; // 当前客户端的用户名public static Socket socket;public static String send_name ; // 当前私聊的用户名public static int send_num ;public static Calendar now ;public static boolean tag = true;String old = new String() ;// 构造函数public frame(String s){send_name = s;start() ;}// 构造函数结束public void run(){f.setTitle("@"+message_frame_erName+" to "+send_name) ; // 设置私聊窗口标题message_frame_to.frame_Threader.add(this) ;f.setLayout(null) ;f.setBounds(200,100,600,500) ;f.setBackground(Color.gray) ;f.setResizable(false) ;panel.setBounds(0, 0, 600, 500) ;f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e) // 私聊窗口关闭{f.setVisible(false) ;message_frame_to.frame_Threader.remove(this) ;tag = false;}}) ;text_input.setBounds(10,400,400,100) ;text_input.setBackground(Color.white) ;text_input.setVisible(true) ;text_input.setFont(new Font("宋体",Font.BOLD,22)); text_input.setForeground(Color.blue);text_message.setBounds(10,70,400,300) ;text_message.setBackground(Color.white) ;text_message.setVisible(true) ;text_message.setFont(new Font("宋体",Font.BOLD,20)); text_message.setForeground(Color.blue);text_message.setEditable(false) ;text_message.selectAll() ;panel.add(text_input) ;panel.add(text_message) ;Label label_1= new Label("Input Area") ;Label label_2= new Label("Message Area") ;label_1.setBounds(10, 370, 400, 30) ;label_1.setBackground(Color.gray) ;label_1.setVisible(true) ;label_1.setFont(new Font("黑体",Font.BOLD , 20)) ; label_1.setForeground(Color.black) ;label_2.setBounds(10, 40, 400, 30) ;label_2.setBackground(Color.gray) ;label_2.setVisible(true) ;label_2.setFont(new Font("黑体",Font.BOLD , 16)) ; label_2.setForeground(Color.black) ;panel.add(label_1) ;panel.add(label_2) ;b.setBounds(450, 440,100, 30) ;b.setBackground(Color.LIGHT_GRAY) ;b.setVisible(true) ;b.setFont(new Font("隶书",Font.BOLD , 20)) ;b.setForeground(Color.black);b.addActionListener(this) ;panel.add(b) ;f.add(panel) ;f.setVisible(true) ;UserName = message_frame_erName ; String inn ;while(true) // 死循环,用来保持私聊窗口的活性{ }} // run函数结束// 私聊窗口按钮监听执行器函数public void actionPerformed(ActionEvent e){if(e.getSource()==b) // 点击发送消息{send_one();text_input.setText("") ;}} // 私聊窗口按钮监听函数结束//私聊消息发送函数public void send_one(){now = Calendar.getInstance();String str = now.getTime().toString() ;String line = text_input.getText();message_frame_to.out.println("%"+send_name);message_frame_to.out.println("@"+UserName);message_frame_to.out.println("&"+UserName+":"+" "+line);old = text_message.getText() ;text_message.setText(old+str+" "+"\n"+UserName+":"+" "+line+"\n") ;} // 私聊消息发送函数结束// 私聊窗口信息显示函数public void write(String inn){now = Calendar.getInstance();String str = now.getTime().toString() ;String ol = text_message.getText() ;text_message.setText(ol+str+" "+"\n"+inn+"\n") ;}// 私聊窗口信息显示函数结束} // 私聊窗口类结束//************************************************************************************* ************************************************************************************** *********************//************************************************************************************* ****** 登录界面类************************************************************************************** class Dlog extends Frame implements ActionListener{Frame D=new Frame("Wellcome To GAGA Chatroom") ;TextArea t=new TextArea() ;Button sure= new Button("Sure") ;Label user_name= new Label("User Name ") ;static ImageIcon icon=new ImageIcon("C:\\scan5.0.jpg") ;static public JLabel p = new JLabel(icon) ;// 构造函数,创建登录窗口界面public Dlog(){D.setLayout(null) ;D.setBackground(Color.gray) ;D.setBounds(400, 260, 450, 300) ;t.setBackground(Color.white) ;t.setBounds(100, 100, 150, 50) ;D.add(t) ;sure.setBounds(260, 100, 70, 30) ;sure.setBackground(Color.lightGray) ;sure.addActionListener(this) ;D.add(sure) ;user_name.setBounds(100, 70, 100, 24) ;user_name.setBackground(Color.gray) ;D.add(user_name) ;p.setBounds(0, 0, 450, 300);D.add(p) ;D.setVisible(true) ;}// 构造函数结束// 登录窗口按钮监听执行器函数public void actionPerformed(ActionEvent e){message_frame_erName=t.getText() ;message_frame_to.out.println("@"+message_frame_erName);D.setVisible(false) ;message_frame_bel_4.setText("User:"+""+message_frame_erName);message_frame_to.f.setVisible(true) ;PlayWav login_music= new PlayWav("C:\\yue1.wav") ;login_music.play() ;}// 登录窗口俺就监听执行器函数}// 登录类结束//************************************************************************************* ************************************************************************************** ******//***************************************************************************** 音乐播放类,支持wav格式********************************************************************class PlayWav{private static AudioInputStream ais=null ;private AudioFormat af=null;private dli=null;private SourceDataLine sdl=null;private final String source ;// 构造函数public PlayWav(String soun){source= soun ;try{ais=AudioSystem.getAudioInputStream(new File(source));af=ais.getFormat();dli=new (SourceDataLine.class,af);sdl=(SourceDataLine)AudioSystem.getLine(dli);}catch(Exception ex){System.err.println(ex);}} // 构造函数结束// 播放函数public void play(){byte[] buff=new byte[102400];int len=0;try{sdl.open(af,102400);sdl.start();while((len=ais.read(buff))>0){sdl.write(buff,0,len);}ais.close();sdl.drain();sdl.close();}catch(Exception ex){System.err.println(ex);}} // 播放函数结束} //音乐播放类结束/* 服务器程序:Server.java* 创建者:XXX PB09210XXX* 创建时间:2011年11月26日* 联系方式:xxx* 版本信息:version 2.0* */package Server;import java.io.*;import .*;import java.util.*;import java.awt.*;import javax.swing.ImageIcon;import java.awt.event.*;import javax.swing.*;// 主类Serverpublic class Server extends ServerSocket implements ActionListener{private static final int SERVER_PORT = 10000; // 服务器端口号private static ArrayList<String> User_List = new ArrayList<String>(); // 存放当前连接服务器的用户列表private static ArrayList<CreateServerThread> Threader = new ArrayList<CreateServerThread>(); // 存放客户端列表,每个元素对应一个客户端private static LinkedList<String> Message_Array = new LinkedList<String>(); // 消息列表,存放等待发送的消息private static int Thread_Counter = 0;private static boolean isClear = true;static Frame f=new Frame("Server 2.0") ;static ImageIcon icon=new ImageIcon("C:\\scan2.jpg") ;static public JLabel panel = new JLabel(icon) ;static public Button bs= new Button("Start") ;static public Button bc=new Button("Cease") ;public static JPasswordField password_input=new JPasswordField () ; public static TextArea status_output=new TextArea() ;public static Label password = new Label("Password") ;public static int tag=0 ;//主函数public static void main(String[] args) throws IOException{new Server(); // 调用Server函数}// Sever函数,用来监听客户端连接public Server() throws IOException{window() ; // 建立服务器的图形界面while(true) // 等待使用者输入正确的密码,开始服务器{if(tag==1){status_output.setText("The sever is working") ;break ;}}new Broadcast() ; // 创建广播类(线程),用来发送消息ServerSocket ss= new ServerSocket(SERVER_PORT) ; // 开启服务器端口try{while(true) // 不断的监听是否有客户端请求连接{Socket socket = ss.accept(); // 一旦有客户端连接,为这个客户端创建一个CreateServerThread类(线程),以便管理new CreateServerThread(socket); // 可以通过找到这个类找到对应的客户端}}catch (IOException e) {}finally{close();}} // Server函数结束// 服务器的界面设计window函数public void window(){f.setLayout(null) ;f.setBounds(300,200,600,500) ;f.setBackground(Color.gray) ;f.setResizable(false) ;f.setVisible(true) ;panel.setBounds(0, 0, 600, 500) ;f.add(panel) ;f.addWindowListener // 监听整个窗口,点击关闭键后直接结束服务器程序(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}. }) ;bs.setBounds(450, 440,100, 30) ;bs.setBackground(Color.LIGHT_GRAY) ;bs.setVisible(true) ;f.add(bs) ;bs.addActionListener(this) ;bc.setBounds(450, 400,100, 30) ;bc.setBackground(Color.LIGHT_GRAY) ;bc.setVisible(true) ;bc.addActionListener(this) ;password_input.setBounds(90,360,100,35) ;// 距离00,x y 以及x y password_input.setBackground(Color.white) ;password_input.setVisible(true) ;panel.add(password_input) ;password.setBounds(10, 360, 60, 30) ;password.setBackground(Color.gray) ;password.setVisible(true) ;panel.add(password) ;status_output.setBounds(10,400,260,50 );status_output.setBackground(Color.white) ;status_output.setVisible(true) ;status_output.setFont(new Font("宋体",Font.BOLD,20));status_output.setEditable(false) ;status_output.setForeground(Color.red);panel.add(status_output) ;}//window函数结束//服务器GUI上按钮监听执行器函数public void actionPerformed(ActionEvent e){if(e.getSource()==bs) // 当按下start按钮后先检测使用者是否输入正确的密码,若是密码正确,服务器开始工作{String key =password_input.getText() ;if(key.equals(""))status_output.setText("Please input password ") ;elseif(key.equals("0911001"))tag=1 ;elsestatus_output.setText("The password is wrong ") ;}if(e.getSource()==bc) // 关闭服务器按钮{tag=0 ;}}// 监听函数结束//********************************************************广播类(线程派生类)********************************************************// 用于发所有建立连接的客户端发送消息class Broadcast extends Thread{public Broadcast(){start();}public void run(){while(true){if (!isClear){// 当isClear为假,说明消息队列里面放有没有发送的消息,广播这些消息String tmp = (String)Message_Array.getFirst(); // 得到消息队列的队列头部的消息for (int i = 0; i < Threader.size(); i++){ // 对于Threader数组里所有元素广播这条消息,因为一个Threader对应一个CreateServerThread进程类,也就对应一个客户端// 对所有连接到服务器的客户端广播这个消息CreateServerThread client = (CreateServerThread)Threader.get(i);client.sendMessage(tmp);}Message_Array.removeFirst(); //移除广播掉的这个消息isClear = Message_Array.size() > 0 ? false : true; // 判断消息队列里还有没有消息,以供继续广播}}}}//广播类结束//******************************************************** 客户端类。
java实训聊天系统报告总结一、项目背景随着互联网的快速发展,人们在日常生活和工作中越来越依赖于网络。
在线聊天成为了人们日常交流的重要方式。
为了满足不同用户对聊天系统的需求,本次实训项目选择开发一款功能完善的Java聊天系统。
二、项目目标1. 设计一款用户界面友好,操作简单的聊天系统。
2. 实现用户的注册和登录功能,保障系统的安全性。
3. 提供实时聊天功能,用户可以通过系统进行文字、图片的交流。
4. 支持多人群聊、私聊的功能。
5. 实现聊天记录的存储和查看。
三、系统架构1. 前端设计本次项目的前端开发使用Java的Swing库进行界面设计,保障用户操作的友好性和系统的易用性。
2. 后端开发后端使用Java语言进行开发,使用Socket实现实时通讯功能,使用MySQL进行用户数据的存储和管理。
四、功能实现1. 用户注册和登录功能用户可以通过系统注册新账号,并使用已有账号进行登录。
系统会对用户输入的信息进行验证,保障系统的安全性。
2. 实时聊天用户可以通过系统进行实时的文字、图片交流,确保用户之间的沟通顺畅和效率。
3. 多人群聊、私聊功能系统支持多人同时进行群聊,同时也支持用户进行私聊。
用户可以根据自己的需求选择不同的聊天方式。
4. 聊天记录存储和查看系统会将用户的聊天记录进行存储,并提供查看功能,用户可以随时查看自己的聊天记录。
3. 数据库设计设计数据库存储用户的基本信息、聊天记录等数据,确保数据的安全性和完整性。
4. 功能实现实现用户注册、登录、实时聊天、群聊、私聊等功能,并保障系统的稳定性和安全性。
六、总结本次实训项目成功设计并开发了一款功能完善的Java聊天系统,满足了用户对聊天系统的基本需求。
通过本次项目的实训,加深了我们对Java语言、数据库设计和网络通讯的理解和实践能力,为我们以后的开发工作积累了丰富的经验。
七、展望在今后的工作中,我们还可以进一步完善系统功能,例如增加语音、视频通话功能,优化系统的性能和用户体验,使系统更加满足用户的需求。
java聊天程序实验报告Java聊天程序实验报告一、引言随着互联网的快速发展,人们之间的交流方式也在不断改变。
聊天程序作为一种实时通信工具,已经成为人们日常生活中必不可少的一部分。
本实验旨在通过使用Java编程语言,设计并实现一个简单的聊天程序,以探索实时通信的原理和机制。
二、实验目的1. 学习和掌握Java编程语言的基本语法和面向对象的编程思想;2. 了解Socket编程的基本原理和实现方式;3. 设计并实现一个简单的聊天程序,实现用户之间的实时通信。
三、实验过程1. 确定程序的基本功能和界面设计。
聊天程序需要实现用户之间的即时通信,并提供简单的用户界面用于输入和显示聊天内容。
2. 使用Java编程语言,创建一个服务器端程序和多个客户端程序。
服务器端程序负责接收和转发客户端的消息,客户端程序负责发送和接收消息。
3. 使用Socket编程,建立服务器和客户端之间的连接。
服务器端程序监听指定的端口,等待客户端的连接请求;客户端程序通过指定服务器的IP地址和端口号,连接到服务器。
4. 实现消息的发送和接收功能。
客户端程序可以通过输入框输入消息,并通过Socket将消息发送到服务器;服务器端程序接收到消息后,将消息转发给其他客户端。
5. 实现消息的显示功能。
客户端程序通过界面显示接收到的消息,并可以将消息保存到本地。
四、实验结果经过实验,我们成功地实现了一个简单的Java聊天程序。
用户可以通过输入框输入消息,并通过服务器端进行消息的转发。
其他客户端可以接收到转发的消息,并在界面上进行显示。
同时,我们还实现了消息的保存功能,用户可以将接收到的消息保存到本地文件中。
五、实验总结通过本次实验,我们深入了解了Java编程语言的基本语法和面向对象的编程思想。
同时,我们也学习了Socket编程的原理和实现方式。
通过实践,我们掌握了如何使用Java编写一个简单的聊天程序,实现用户之间的实时通信。
然而,本实验只是一个简单的聊天程序,还有很多可以改进和扩展的地方。
JAVA聊天程序大作业报告程序编写者:刘永峰学号:E10814018专业: 计算机科学与技术2班分组:个人为一组编写日期: 自从11月16号老师讲了大作业要求及如何编写便开始了,大概用了3天时间编号了程序,不过惭愧的是写总结拖了这么长时间,呵呵报告如下:实验名称:聊天程序实验目的: 1编写一个客户服务器聊天室程序2 掌握Java程序的界面处理3 了解聊天软件的基本原理实验内容:聊天室程序功能简述:1 窗口占有者2 消息接收者3 消息输入框4消息接收框如下图所示:实验过程:(1)采用JCreator作为开发工具,JA V A 为开发语言。
(2)使用JA V A 的jLSendMss 和jLReceiveMss 这两个类可以像本地输入输出那么方便。
(3)窗口适配器private MyWindowAdapter mwa=null;(4) 通讯用成员变量private byte[] receiveBuf=new byte[1000];private byte[] sendBuf=null;private DatagramSocket datagramServer=null;private DatagramSocket datagramClient=null;private DatagramPacket receivePacket=null;private DatagramPacket sendPacket=null;private static final int PORT=5000;private InetAddress inetAddr=null;private Server server=null;private String machineName=null;private String sendMss=null;界面如下:其中机器名或IP地址不可编程,下面的输入地址栏为聊天对方的地址可输入对方的地址,发送消息亦不可编程,下面的输入框即可输入要发送的内容,如果要发送,点击发送按钮即可,如果要重新写入,点击清空即可,如果输入的对方地址正确,则出现发送成功提示框如果对方地址不正确,出现发送失败提示框,如下:实验总结主要参考了《JA V A 程序设计教程(第二版)》(清华出版社,雍俊海编著),了解到界面编程的基本要点。
java聊天程序实验报告《Java聊天程序实验报告》摘要:本实验报告旨在介绍和分析我们设计并实现的基于Java的聊天程序。
通过该程序,用户可以在网络上进行实时的文字交流,实现了简单的聊天功能。
我们将介绍程序的设计思路、实现过程、功能特点以及存在的问题和改进方向。
一、设计思路我们的聊天程序采用了客户端-服务器架构,通过Socket通信实现了用户之间的数据传输。
客户端和服务器端分别使用了Java的Socket和ServerSocket类来建立连接和进行通信。
客户端可以向服务器发送消息并接收其他用户的消息,服务器负责转发消息给其他在线用户。
二、实现过程在实现过程中,我们首先设计了程序的基本框架,包括客户端和服务器端的代码结构。
然后,我们使用Socket和ServerSocket类来建立连接和进行数据传输。
客户端和服务器端分别使用了多线程来处理连接请求和消息转发,以保证程序的稳定性和并发性。
三、功能特点我们的聊天程序具有以下功能特点:1. 用户注册和登录:用户可以注册新账号并登录到服务器,实现了用户身份的识别和管理。
2. 实时聊天:用户可以在聊天室中实时发送和接收消息,与其他在线用户进行文字交流。
3. 离线消息:服务器可以保存用户的离线消息,并在用户上线时进行推送,确保用户不会错过重要消息。
四、存在的问题和改进方向在实验过程中,我们发现了一些问题和改进方向:1. 安全性问题:目前我们的程序还没有实现用户身份验证和消息加密等安全机制,存在一定的安全风险。
2. 用户体验:目前用户界面较为简陋,可以进一步优化界面设计和交互体验。
3. 功能扩展:可以考虑增加文件传输、群聊等功能,丰富程序的功能特点。
结论:通过本次实验,我们成功设计并实现了基于Java的聊天程序,实现了简单的聊天功能。
在未来,我们将继续改进程序,提高安全性和用户体验,丰富功能特点,使程序更加完善和实用。
一、实验内容实验题目:1、使用URL访问用户指定网站,获取该网页的HTML代码显示给用户,并能保存至指定文件中。
2、使用ServerSockt,Socket对象实现两个用户之间的端到端聊天。
要求:采用UI界面设计,界面友好。
二、实验过程(这是实验报告极其重要的内容。
要抓住重点,可以从理论和实践两个方面考虑。
这部分要写明依据什么知识点以及使用方法进行实验以及实验步骤。
不要简单照抄实习指导,更不可写一大堆源代码)题目1、1、分析题目,了解URL类及其方法。
2、设计一个模拟浏览器界面,有一个文本框,文本区域,一个搜索按钮,一个保存按钮。
3、在搜索事件里面写获取HTML的代码,在保存你面写将内容保存至文件中。
题目2、1、分析题目,了解import .*,包下用到的一些类,比如URL, Socket和ServerSocket,以及这些类的方法,根据要实现的功能,进行调用。
了解端到端的通讯,以及怎样建立连接。
2、设计界面:服务器界面,客户端界面。
3、写出对内容的读写代码,注意哪部分功能,在什么时候实现,应该写在哪部分。
以及怎样通信:如图三、实验结果(应先列出测试数据,要写明实验的现象,实验数据的处理等。
对于实验结果的表述,一般有三种方法:文字叙述(根据实验目的将实验结果系统化、条理化,用准确的专业术语客观地描述实验现象和结果,要有时间顺序以及各项指标在时间上的关系),图表(用表格或坐标图的方式使实验结果突出、清晰,便于相互比较,尤其适合于分组较多,且各组观察指标一致的实验,使组间异同一目了然;每一图表应有表目和计量单位,应说明一定的中心问题),屏幕截图(实验结果也可以是屏幕截图,充分表明实验的实际情况)。
在实验报告中,可任选其中一种或几种方法并用,以获得最佳效果。
)题目一、界面与结果截图:题目2、服务器端截屏:客户端截屏:四、讨论与分析(这是实验报告的主要部分。
根据相关的知识点以及编程规范和经验对所得到的实验结果进行解释和分析。
Java聊天室系统程序设计实验报告院(系):信息与通信工程系专业:计算机应用技术班级:学号:姓名:指导老师:2013/6/8目录第一部分:系统设计总述............................................................................1.设计目的:......................................................................................2.设计总体要求:..................................................................................3.实现目的:...................................................................................... 第二部分:系统需求分析............................................................................1.系统任务描述....................................................................................2.系统功能分析....................................................................................3.系统可行性分析.................................................................................. 第三部分:系统设计................................................................................1.系统总体结构设计................................................................................2.系统主体的处理流程..............................................................................3.系统流程逻辑.................................................................................... 第四部分:代码分析................................................................................1.服务器端部分代码................................................................................2.客户端部分代码.................................................................................. 第五部分:系统的具体实现..........................................................................界面设计.......................................................................................... 第六部分:小结.................................................................................... 第七部分:参考文献................................................................................ 第一部分:系统设计总述1.设计目的:1.在开发技术和过程中,能够充分学习和使用JAVA的技术,进一步培养学生面向对象程序设计的思想,加深对面向对象程序设计特性的理解。
JAVA聊天程序设计代码及报告import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.Scanner;public class ChatClientpublic static void main(String[] args)final String HOST_NAME = "localhost";final int PORT_NUMBER = 1234;trySocket socket = new Socket(HOST_NAME, PORT_NUMBER);System.out.println("Connected to chat server!");BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream());PrintWriter writer = new PrintWriter(socket.getOutputStream(, true);// read user input in a separate threadThread inputThread = new Thread(( ->Scanner scanner = new Scanner(System.in);while (true)String userInput = scanner.nextLine(;writer.println(userInput);}});inputThread.start(;// continuously read server responsesString serverResponse;while ((serverResponse = reader.readLine() != null)System.out.println("Server: " + serverResponse);}} catch (Exception e)System.out.println("Error: " + e.getMessage();}}该聊天程序是一个基于TCP协议的客户端程序,使用了Java Socket 进行通信。
java实训聊天系统报告总结在Java实训中,我们成功地设计和实现了一个聊天系统。
该系统具有以下功能:用户注册、登录、加好友、发送消息等。
在设计这个系统之前,我们进行了许多需求分析的工作,确定了系统的具体功能和要求。
然后,我们设计了系统的架构,包括前端界面和后端数据库的设计。
在开发过程中,我们采用了Spring Boot框架,使用了MySQL作为后端数据库。
由于我们的系统需要进行实时通信,因此我们还使用了基于WebSocket的技术。
在实际的开发过程中,我们首先完成了用户注册和登录的功能。
用户可以通过输入用户名和密码进行注册,并在登录页面输入正确的用户名和密码进行登录。
如果登录成功,系统将会跳转到聊天界面。
如果没有注册或者用户名密码输入错误,系统会给出相应的提示信息。
接下来,我们实现了添加好友的功能。
用户可以通过输入好友的用户名来添加好友。
当用户输入好友的用户名并点击添加按钮时,系统会检查数据库中是否存在该用户。
如果存在,则将该用户添加到当前用户的好友列表中;如果不存在,则给出相应的提示信息。
我们实现了发送消息的功能。
用户可以在输入框中输入消息,并点击发送按钮来发送消息。
在点击发送按钮后,用户的好友列表中的用户会收到消息。
用户可以选择查看已发送和已接受的消息。
在整个开发过程中,我们遇到了许多问题,并从中学到了许多经验。
我们学会了如何进行需求分析,如何将需求转化为具体的功能和要求。
我们学会了如何设计系统的架构,并根据架构来进行具体的开发工作。
我们学会了如何解决问题和调试程序,在遇到问题时能够快速找到解决方法。
通过这个实训项目,我们不仅学到了Java语言和Spring Boot框架的相关知识,还学会了团队合作和项目管理的技巧。
我们在与团队成员的合作中学会了沟通和协调的重要性,以及如何高效地分工合作。
在整个项目过程中,我们对实际的软件开发流程有了更深入的了解,提高了我们的编程能力和解决问题的能力。
Java网络通信一、实验内容1、图形界面编程,利用TCP的socket或者UDP编写,客户端和服务器端程序可以进行多次对话。
2、利用程序,访问一个网站,将指定的一个页面保存到本地。
二、实验目的1、学习java网络通信中的Socket编程,熟悉TCP和UDP的应用。
2、学习网络编程的基础内容,了解TCP/IP协议的简单概念,和JAVA结合编程。
3、实现事件的处理,比如说鼠标的单击,按下等操作。
三、实验分析1、UDP中Socket中的编程也分为服务器和客户端,与TCP不同的是它无需建立、拆除连接,直接将信息打包传向指定的目的地,使用起来比TCP要简单一些。
2、第三个程序,我写了一个简单的网页浏览器,功能不是很全面,但是能实现,查看源文件,保存,全屏,还原等功能,还能自动修正输入的网络地址。
就是有时候图片显示还有点问题。
主要用到了JEditorPane中的setPage()解析html文件。
四、程序代码1、UDP服务端import java.io.*;import .*;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class UDPServer extends JFrame{JTextField jtf=new JTextField(30);JTextArea jta=new JTextArea();JButton jb=new JButton("发送");JPanel jp=new JPanel();DatagramSocket serversocket=null;DatagramPacket serverpacket=null,serverpacket1=null;InetAddress address;int port;String datagram;public UDPServer(){jp.setLayout(new FlowLayout());jp.add(jtf);jp.add(jb);this.getContentPane().add(jp,BorderLayout.SOUTH );this.getContentPane().add(new JScrollPane(jta),BorderLayout.CENTER);jta.setEditable(false);jb.addActionListener(new buttonListener());setTitle("服务器");setSize(600,400);setVisible(true);this.addWindowListener(new winAdpt());try{serversocket=new DatagramSocket(5555);jta.append("服务器已启动正在监听端口5555..."+"\n");}catch(Exception eg){}while(true){try{byte[] databuf=new byte[512];serverpacket=new DatagramPacket(databuf,512);serversocket.receive(serverpacket);address=serverpacket.getAddress();port=serverpacket.getPort();datagram=new String(serverpacket.getData());jta.append(datagram+"\n");}catch(IOException ex){jta.append(ex.toString()+"\n");}}}public static void main(String[] args) {new UDPServer();}class winAdpt extends WindowAdapter{public void windowClosing(WindowEvent e){try{serversocket.close();serversocket=null;}catch(Exception ea){}e.getWindow().dispose();System.exit(0);}}class buttonListener implements ActionListener{public void actionPerformed(ActionEvent e){try{byte[] databuf=new byte[512];datagram=jtf.getText();databuf=datagram.getBytes();serverpacket1=newDatagramPacket(databuf,databuf.length,address,port);serversocket.send(serverpacket1);}catch(IOException ex){jta.append(e.toString()+"\n");}}}}2、UDP客户端import java.io.*;import .*;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class UDPClient extends JFrame{JTextField jtf=new JTextField(30);JTextArea jta=new JTextArea();JButton jb=new JButton("发送");JPanel jp=new JPanel();DatagramSocket socket=null;DatagramPacket packet=null,packet1=null;String datagram=null;InetAddress address=null;public UDPClient(){jp.setLayout(new FlowLayout());jp.add(jtf);jp.add(jb);this.getContentPane().add(jp,BorderLayout.SOUTH );this.getContentPane().add(new JScrollPane(jta),BorderLayout.CENTER);jta.setEditable(false);jb.addActionListener(new buttonListener());setTitle("客户端");setSize(600,400);setVisible(true);this.addWindowListener(new winAdpt());try{socket=new DatagramSocket(6666);address=InetAddress.getByName("127.0.0.1");}catch(IOException eg){}while(true){try{byte[] databuf=new byte[512];packet=new DatagramPacket(databuf,512);socket.receive(packet);datagram=new String(packet.getData());jta.append(datagram+"\n");}catch(Exception e){}}}public static void main(String[] args) {new UDPClient();}class buttonListener implements ActionListener{public void actionPerformed(ActionEvent e){try{datagram=jtf.getText();byte[] databuf=datagram.getBytes();packet1=newDatagramPacket(databuf,databuf.length,address,5555);socket.send(packet1);}catch(IOException ex){jta.append(e.toString()+"\n");}}}class winAdpt extends WindowAdapter{public void windowClosing(WindowEvent e){try{socket.close();socket=null;}catch(Exception ea){}e.getWindow().dispose();System.exit(0);}}}3、浏览器程序MyWebBrowser.java文件import .*;import javax.swing.*;import javax.swing.event.*;import java.awt.*;import java.awt.event.*;import java.util.*;import java.io.*;public class MyWebBrowser implements ActionListener{/////////窗口////////////////////////////////////JFrame mainwindow=new JFrame("我的浏览器"); //主窗口Container contentpane=mainwindow.getContentPane();//内容窗格JWindow fullscreen=new JWindow(mainwindow); //建立全屏窗格Container contentpane1=fullscreen.getContentPane();///////////菜单///////////////////JMenuBar menuBar=new JMenuBar(); //创建菜单条JMenu menu_file=new JMenu("文件"); //创建“文件”菜单项JMenuItem file_saveas=new JMenuItem("另存为"); //“另存为”菜单项子项JMenuItem file_exit=new JMenuItem("退出");JMenu menu_edit=new JMenu("编辑"); //创建“编辑”菜单项JMenuItem edit_cut=new JMenuItem("剪切"); //“剪切”菜单项子项JMenuItem edit_copy=new JMenuItem("复制");JMenuItem edit_paste=new JMenuItem("粘贴");JMenu menu_view=new JMenu("视图"); //创建“视图”菜单项JPopupMenu fromto=new JPopupMenu("转到"); //“转到”菜单项子项JMenuItem pop_backward=new JMenuItem("后退"); //”后退“JMenuItem pop_forward =new JMenuItem("前进"); //“前进”JMenuItem view_reload=new JMenuItem("刷新");JMenuItem view_getsource=new JMenuItem("源文件");JMenuItem view_fullscreen=new JMenuItem("全屏");JMenu menu_help=new JMenu("帮助"); //“帮助”菜单项JMenuItem aboutme=new JMenuItem("关于");///////////////////////工具条////////////////JToolBar toolbar=new JToolBar(); //定义工具条JButton tool_backward=new JButton("后退"); //“后退”JButton tool_forward=new JButton("前进"); //“前进”JLabel prompt=new JLabel("地址:"); //地址标签JTextField address=new JTextField(10); //文本框,用于输入URLJButton go=new JButton("转到/刷新"); //转到按钮JButton stop=new JButton("停止");JButton recover= new JButton("还原"); //从最大化还原成最小化时的按钮,构造时不添加////////////////////////////////内容框////////////////////////// JEditorPane editorpane= new JEditorPane ();JScrollPane scrollpane= new JScrollPane ();JTabbedPane tabbedpane=new JTabbedPane(); //创建//////////////////////其他变量//////////////////////////String url;ArrayList history=new ArrayList(); //用于保存历史记录int historyindex;Dimension initsize=new Dimension(900,600);Dimension maxsize = Toolkit.getDefaultToolkit().getScreenSize();//屏幕大小////////构造函数///////////////////////////public MyWebBrowser(){menu_file.add(file_saveas); //将菜单子项加入到菜单项menu_file.addSeparator(); //加一条分割线menu_file.add(file_exit);menuBar.add(menu_file); //将“文件”菜单项加入到菜单条中menu_edit.add(edit_cut);menu_edit.add(edit_copy);menu_edit.add(edit_paste);menuBar.add(menu_edit);fromto.add(pop_backward);fromto.add(pop_forward);menu_view.add(fromto);menu_view.add(view_reload);menu_view.addSeparator(); //分割线menu_view.add(view_getsource);menu_view.add(view_fullscreen);menuBar.add(menu_view);menu_help.add(aboutme);menuBar.add(menu_help);mainwindow.setJMenuBar(menuBar); //把菜单条加入到整个JFrame容器中toolbar.add(tool_backward);toolbar.add(tool_forward);toolbar.add(prompt);toolbar.add(address);toolbar.add(go);toolbar.add(stop);contentpane.add(toolbar,BorderLayout.NORTH); //添加工具条editorpane.setEditable(false); //设置文本区域不能写scrollpane.getViewport().add(editorpane);//窗格可视区添加JEditorpanecontentpane.add(scrollpane,BorderLayout.CENTER);//添加滚动窗格file_saveas.addActionListener(this);//添加事件监听file_exit.addActionListener(this);edit_cut.addActionListener(this);edit_copy.addActionListener(this);edit_paste.addActionListener(this);pop_backward.addActionListener(this);pop_forward.addActionListener(this);view_reload.addActionListener(this);view_getsource.addActionListener(this);view_fullscreen.addActionListener(this);aboutme.addActionListener(this);tool_backward.addActionListener(this);tool_forward.addActionListener(this);address.addActionListener(this);go.addActionListener(this);stop.addActionListener(this);mainwindow.setSize(initsize);mainwindow.setVisible(true); }/////////事件处理函数//////////////////////public void actionPerformed(ActionEvent e){url=address.getText().trim(); //获取URLif(e.getActionCommand()=="转到/刷新"||e.getSource()==address||e.getActionCommand()=="刷新"){if(url.length()>0){if(!url.startsWith("http://"))url="http://"+url;if(!url.endsWith("/"))url=url+"/";try{editorpane.setPage(url);address.setText(url);history.add(url);historyindex=history.size()-1;}catch(Exception ex){JOptionPane.showMessageDialog (mainwindow,"无法打开该搜索页","网页浏览器",JOptionPane.ERROR_MESSAGE);}}}else if(e.getActionCommand()=="后退"){historyindex--;if(historyindex<0)historyindex=0;try{url=(String)history.get(historyindex);editorpane.setPage(url);address.setText(url);}catch(Exception ex){JOptionPane.showMessageDialog (mainwindow,"无法打开该搜索页","网页浏览器",JOptionPane.ERROR_MESSAGE);}}else if(e.getActionCommand()=="前进"){historyindex++;if(historyindex>=history.size())historyindex=history.size()-1;try{url=(String)history.get(historyindex);editorpane.setPage(url);address.setText(url);}catch(Exception ex){JOptionPane.showMessageDialog (mainwindow,"无法打开该搜索页","网页浏览器",JOptionPane.ERROR_MESSAGE);}}else if(e.getActionCommand()=="源文件"||e.getSource()==view_getsource){if(url.length()>0)new sourcefile(url);}else if(e.getActionCommand()=="全屏"){mainwindow.setVisible(false);toolbar.add(recover);contentpane1.add(toolbar,BorderLayout.NORTH);contentpane1.add(scrollpane, BorderLayout.CENTER);recover.addActionListener(new ActionListener (){public void actionPerformed(ActionEvent e1){contentpane1.remove(scrollpane);toolbar.remove(recover);contentpane1.remove(toolbar);fullscreen.setVisible (false);//还原mainwindow.add(toolbar,BorderLayout.NORTH); //添加工具条mainwindow.add(scrollpane,BorderLayout.CENTER);mainwindow.setSize(initsize);mainwindow.setVisible(true);}});fullscreen.setSize (maxsize);fullscreen.setVisible (true);}else if(e.getActionCommand()=="关于"){JOptionPane.showMessageDialog (mainwindow,"我的浏览器\n版本:1.0","关于",JOptionPane.CLOSED_OPTION);}}public static void main(String[] args) {new MyWebBrowser();}}Source_file.java文件import java.awt.*;import java.awt.event.*;import javax.swing.*;import .*;import java.io.*;public class sourcefile {JFrame source=new JFrame("源文件");Container containpane=source.getContentPane();JTextArea showfile= new JTextArea ();JScrollPane scrollpane= new JScrollPane ();JPanel panel=new JPanel(); //用于存放下面两个按钮JButton save=new JButton("保存");JButton exit=new JButton("退出");private String inline;public sourcefile(String str){showfile.setEditable(false);scrollpane.getViewport().add(showfile);containpane.add(scrollpane,BorderLayout.CENTER);panel.setLayout(new FlowLayout());panel.add(save);panel.add(exit);containpane.add(panel,BorderLayout.SOUTH);try{URL myurl=new URL(str);BufferedReader dis=new BufferedReader(new InputStreamReader(myurl.openStream()));while((inline=dis.readLine())!=null){showfile.append(inline+"\n");}}catch(MalformedURLException e){JOptionPane.showMessageDialog (source,"无法打开搜索页","网页浏览器",JOptionPane.ERROR_MESSAGE);}catch(IOException e){JOptionPane.showMessageDialog (source,"无法打开搜索页","网页浏览器",JOptionPane.ERROR_MESSAGE);}source.setSize(600,400);source.setVisible(true);}}。