WEB开发网
开发学院WEB开发Jsp 大学JAVA实验五 阅读

大学JAVA实验五

 2009-11-10 21:00:37 来源:WEB开发网   
核心提示:指定不同协议的URL地址,获得资源文件的内容和属性URLStudy.javapackage first;import java.awt.FileDialog;import java.awt.Font;import java.awt.TextArea;import java.io.FileWriter;import ja
指定不同协议的URL地址,获得资源文件的内容和属性

URLStudy.java

package first;

import java.awt.FileDialog;
import java.awt.Font;
import java.awt.TextArea;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PRintWriter;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class URLStudy extends JFrame {

private static final long serialVersionUID = 1L;
private Font font = new Font("宋体", Font.CENTER_BASELINE, 13);
TextArea textarea = new TextArea();
JButton button[] = new JButton[3];
String buttonName[] = { "确定", "取消", "保存文件" };
JLabel label = new JLabel("请输入URL地址:");
JTextField urlfield = new JTextField(20);

JPanel panel = new JPanel();

URLStudyListener listener = new URLStudyListener(this);

private String file = "";

private FileDialog filesave;

public URLStudy() {
  
 super.setTitle("资源文件的内容和属性查看器");
 
 ImageIcon icon = new ImageIcon("195032.jpg");
 setIconImage(icon.getImage());
 
 textarea.setFont(font);
 label.setFont(font);
 urlfield.setFont(font);
 
 panel.add(label);
 panel.add(urlfield);

 for (int i = 0; i < buttonName.length; i++) {
  button[i] = new JButton(buttonName[i]);
  button[i].addActionListener(listener);
  button[i].setFont(font);
  panel.add(button[i]);
 }
 super.setDefaultCloSEOperation(EXIT_ON_CLOSE);
 super.add(textarea, "Center");
 super.add(panel, "South");
 super.setLocation(250, 200);
 super.setSize(600, 400);
 super.setVisible(true);
 super.setResizable(true);
 
 
 filesave = new FileDialog(this, "保存文件-----XiaoHuanJie", FileDialog.SAVE);
}

public void saveFile() {
 String dangqianwenjian = textarea.getText();
 try {
  if (file.isEmpty()) {
  filesave.setVisible(true);
  String direct = filesave.getDirectory();
  String filename = filesave.getFile();

  if ((direct != null) && (filename != null)) {
   file = direct + filename;
   PrintWriter pw = new PrintWriter(new FileWriter(file));
   pw.println(dangqianwenjian);
   pw.flush();
   pw.close();
  }
  } else {
  PrintWriter pw = new PrintWriter(new FileWriter(file));
  pw.println(dangqianwenjian);
  pw.flush();
  pw.close();
  }
 } catch (IOException e) {
  e.printStackTrace();
 }
}

public static void main(String[] args) {
 new URLStudy();
}
}


URLStudyListener.java

package first;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.swing.JOptionPane;

public class URLStudyListener implements ActionListener {
BufferedReader br;
URLStudy urlstudy;

public URLStudyListener(URLStudy urlstudy) {
 this.urlstudy = urlstudy;
}

@Override
public void actionPerformed(ActionEvent ae) {
 String command = ae.getActionCommand();
 if (command.equals("确定")) {
  try {
  URL url = new URL(((urlstudy.urlfield).getText()).trim());
  br = new BufferedReader(new InputStreamReader(url.openStream()));
  while (br.readLine() != null) {
   urlstudy.textarea.append(br.readLine() + "\n");
  }
  } catch (IOException e) {

  JOptionPane.showMessageDialog(null, "您输入的URL地址错误!", "系统提示",
   JOptionPane.ERROR_MESSAGE);

  }
 } else if (command.equals("取消")) {
  (urlstudy.urlfield).setText("");
 } else if (command.equals("保存文件")) {
  urlstudy.saveFile();
 }
}
}


(1)增加上线功能。离线后,将【离线】按钮变成【上线】按钮,单击可再次申请建立连接。
(2)将文本区中对方和己方的字符串以不同的字体区别显示。
(3)发送带格式的字符串。
(4)增加复制功能,将文本区中的若干选中字符串复制到文本行中。
(5)增加若干图标作为表情,发送表情图标。
(6)增加对方信息到达时的语音提示。
(7)将聊天记录存储到文件中。

MyQQServer.java

package second;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;

public class MyQQServer {

public static void main(String[] args) {
 Hashtable<String, DataOutputStream> userList = new Hashtable<String, DataOutputStream>();
 String name;
 DataInputStream dis;
 DataOutputStream dos;

 try {
  ServerSocket serversocket = new ServerSocket(8088);
  while (true) {
  Socket socket = serversocket.accept();
  dis = new DataInputStream(socket.getInputStream());
  dos = new DataOutputStream(socket.getOutputStream());

  name = dis.readUTF();

  userList.put(name, dos);

  new QQServerReader(name, dis, userList).start();
  }
 } catch (IOException e) {

  e.printStackTrace();
 }
}
}

class QQServerReader extends Thread {

private String name;
private DataInputStream dis;

private Hashtable<String, DataOutputStream> userList;

public QQServerReader(String name, DataInputStream dis,
  Hashtable<String, DataOutputStream> userList) {
 // super();
 this.name = name;
 this.dis = dis;
 this.userList = userList;
}

@Override
public void run() {
 String info;
 Date date1 = new Date();
 SimpleDateFormat sdf1 = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
 String time = "\t\t" + sdf1.format(date1);

 transmitMessage(name + " 上线 !", "-------系统消息-------" + time);
 
 while (true) {

  try {

  info = dis.readUTF();
  if (info.equals("^%#$^$jg4653|+=--09-89jh)*")) {// 暗号吻合,该用户退出聊天室
   DataOutputStream dos = (DataOutputStream) userList
    .get(name);

   dos.close();
   dis.close();
   userList.remove(name);
   Date date2 = new Date();
   SimpleDateFormat sdf2 = new SimpleDateFormat(
    "yy-MM-dd HH:mm:ss");
   time = "\t\t" + sdf2.format(date2);

   transmitMessage(name + " 退出聊天室啦 !", "-------系统提示-------"
    + time);
   break;
  } else if (info.equals("L^%#$5@#h(8yh^+_)_)(=78UTh*%@!")) {// 暗号吻合,该用户离线
   //info = "";
   userList.remove(name);
   Date date2 = new Date();
   SimpleDateFormat sdf2 = new SimpleDateFormat(
    "yy-MM-dd HH:mm:ss");
   time = "\t\t" + sdf2.format(date2);

   transmitMessage(name + " 离线 !", "-------系统提示-------" + time);
   break;
  } else if (info.equals("^&%()&(*85KJ$%@+_9)(80(8()*)(")) {// 暗号吻合,该用户重新上线
   DataOutputStream dos = (DataOutputStream) userList
    .get(name);
   userList.put(name, dos);
  } else if (info.length() > 0) {
   Date date3 = new Date();
   SimpleDateFormat sdf3 = new SimpleDateFormat(
    "yy-MM-dd HH:mm:ss");
   time = "\t\t" + sdf3.format(date3);

   transmitMessage(info, name + time);
  }
  } catch (IOException e) {
  e.printStackTrace();
  }
 }
}

public void transmitMessage(String msg, String name) {
 Collection<DataOutputStream> doses = userList.values();
 DataOutputStream dos;

 // 把信息发送给所有在线的用户
 for (Object o : doses) {
  dos = (DataOutputStream) o;
  try {
  dos.writeUTF(name + "\n" + msg + "\n");
  } catch (IOException e) {

  e.printStackTrace();
  }
 }
}

}


MyQQClient.java

package second;

import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class MyQQClient {

private String name;
private Socket socket;
private DataInputStream dis;
private DataOutputStream dos;
JFrame frame;
private TextArea oldInfoArea;
private TextArea newInfoArea;
private boolean runnable=true;
private Font font;

private File file;

ImageIcon icon;

JButton button[] = new JButton[4];

public MyQQClient() {

 runnable = true;
 frame = new JFrame("QQ客户端");

 icon = new ImageIcon("195032.jpg");
 frame.setIconImage(icon.getImage());

 oldInfoArea = new TextArea(15, 20);
 oldInfoArea.setEditable(false);
 newInfoArea = new TextArea(8,20);

 font = new Font("宋体", Font.CENTER_BASELINE, 13);
 oldInfoArea.setFont(font);
 newInfoArea.setFont(font);
 MyQQKeyListener keylistener =new MyQQKeyListener(this);
 
 newInfoArea.addKeyListener(keylistener);
 
 MyQQClientListener listener = new MyQQClientListener(this);

 String buttonName[] = { "表情", "离线", "聊天记录", "发送" };

 Panel panel = new Panel();
 panel.setLayout(new GridLayout(1, 4));

 for (int i = 0; i < buttonName.length; i++) {
  button[i] = new JButton(buttonName[i]);
  button[i].setFont(font);
  button[i].addActionListener(listener);
  panel.add(button[i]);
 }

 frame.add(this.oldInfoArea, "North");
 frame.add(this.newInfoArea, "Center");
 frame.add(panel, "South");

 frame.addWindowListener(new WindowAdapter() {

  @Override
  public void windowClosing(WindowEvent e) {

  int option = JOptionPane.showConfirmDialog(null, "是否完全退出此次聊天?",
   "系统提示", JOptionPane.YES_NO_OPTION,
   JOptionPane.QUESTION_MESSAGE);
  if (option == JOptionPane.YES_OPTION)
   // System.exit(0);
   MyQQClient.this.shutDown();
  }
 });

 frame.setSize(500, 400);
 frame.setLocation(300, 200);
 frame.setResizable(false);

}

public static void main(String[] args) {
 MyQQClient QQClient = new MyQQClient();
 QQClient.inputName();
 QQClient.connect();
 QQClient.createThread();

}

public void saveFile() {
 String oldInfo = oldInfoArea.getText();
 try {
  PrintWriter pw = new PrintWriter(new FileWriter(file, true));// true,不覆盖已有文件

  pw.println(oldInfo);
  pw.flush();
  pw.close();
 } catch (IOException e) {
  e.printStackTrace();
 }

}

// 检查是否存在目标文件,不存在就新建一个
public void init() {
 if (file == null) {
  file = new File(name + ".employee");
  try {
  file.createNewFile();
  } catch (IOException e) {
  e.printStackTrace();
  }
 }
}

public void xiaXian() {
 try {
  dos.writeUTF("L^%#$5@#h(8yh^+_)_)(=78UTh*%@!");// 暗号, 告诉服务器,离线了
  this.runnable=false;
 } catch (IOException e) {
  e.printStackTrace();
 }
}

public void shangXian() {
 try {
  this.runnable=true;
  this.connect();
  dos.writeUTF("^&%()&(*85KJ$%@+_9)(80(8()*)(");// 暗号, 告诉服务器,重新上线
 } catch (IOException e) {
  e.printStackTrace();
 }
}

public void shutDown() {
 try {
  dos.writeUTF("^%#$^$jg4653|+=--09-89jh)*");// 暗号, 告诉服务器,下线了
  Thread.sleep(500);
  saveFile();// 退出时将聊天记录一次性保存
  this.stop();

  //dis.close();
  dos.close();
  this.socket.close();
 } catch (IOException e) {
  e.printStackTrace();
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 System.exit(0);// 聊天窗口退出
}

public void connect() {
 try {
  socket = new Socket("127.0.0.1", 8088);
 } catch (UnknownHostException e1) {
  System.out.println("连接服务器失败!");
  e1.printStackTrace();
 } catch (IOException e1) {
  e1.printStackTrace();
 }
 try {
  dos = new DataOutputStream(socket.getOutputStream());
  dis = new DataInputStream(socket.getInputStream());
  dos.writeUTF(name);// 将本用户的姓名发送给服务器
 } catch (IOException e) {
  e.printStackTrace();
 }
}

public void createThread() {
 MyQQClientReader reader = new MyQQClientReader(this);
 reader.start();
}

public void inputName() {

 String name = (javax.swing.JOptionPane.showInputDialog("请输入您的昵称:"))
  .trim();
 if (name == null || name.equals("")) {// 不接受散客聊天
  JOptionPane.showMessageDialog(null, "昵称不能为空哦,请输入您的昵称!", "系统提示",
   JOptionPane.ERROR_MESSAGE);

  inputName();

 } else {
  this.setName(name);
 }
 init();
 frame.setTitle(name);
 frame.setVisible(true);
}

public void stop() {
 runnable = false;
}

public boolean isRunnable() {
 return runnable;
}

public DataInputStream getDis() {
 return dis;
}

public DataOutputStream getDos() {
 return dos;
}

public TextArea getOldTextArea() {
 return oldInfoArea;
}

public TextArea getNewTextArea() {
 return newInfoArea;
}

public void setName(String name) {
 this.name = name;
}

}


MyQQClientListener.java

package second;

import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

//MyQQClientLister监听器
class MyQQClientListener implements ActionListener {
MyQQClient myQQClient;
String command ;

public MyQQClientListener(MyQQClient myQQClient) {
 this.myQQClient = myQQClient;
}

public void actionPerformed(ActionEvent ae) {
 command = ae.getActionCommand();
 if (command.equals("发送")) {

  TextArea textArea = myQQClient.getNewTextArea();
  String info = textArea.getText();

  try {
  myQQClient.getDos().writeUTF(info);
  } catch (IOException e1) {
  e1.printStackTrace();
  }

  textArea.setText("");
  textArea.requestFocus();
 } else if (command.equals("离线")) {
  myQQClient.button[1].setText("上线");
  myQQClient.xiaXian();
 } else if (command.equals("上线")) {
  myQQClient.button[1].setText("离线");
  myQQClient.shangXian();
 }else if(command.equals("聊天记录")){
  
 }
}
}


MyQQKeyListener.java

package second;

import java.awt.TextArea;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;

public class MyQQKeyListener implements KeyListener {
MyQQClient myQQClient;

MyQQClientListener myQQClientListener;

public MyQQKeyListener(MyQQClientListener myQQClientListener) {
 this.myQQClientListener = myQQClientListener;
}

public MyQQKeyListener(MyQQClient myQQClient) {
 this.myQQClient = myQQClient;
}

@Override
public void keyPressed(KeyEvent ke) {
 if (ke.getKeyCode() == KeyEvent.VK_ENTER && ke.isControlDown()) {
  TextArea textArea = myQQClient.getNewTextArea();
  String info = textArea.getText();

  try {
  myQQClient.getDos().writeUTF(info);
  } catch (IOException e1) {
  e1.printStackTrace();
  }

  textArea.setText("");
  textArea.requestFocus();
 }
}

@Override
public void keyReleased(KeyEvent e) {

}

@Override
public void keyTyped(KeyEvent e) {

}
}

MyQQClientReader.java


package second;

import java.awt.Color;
import java.awt.TextArea;
import java.io.DataInputStream;
import java.io.IOException;

class MyQQClientReader extends Thread {

private MyQQClient myQQClient;

public MyQQClientReader(MyQQClient myQQClient) {
 this.myQQClient = myQQClient;
}

@Override
public void run() {
 String info;

 int a = (int) (Math.random() * 255);
 int b = (int) (Math.random() * 255);
 int c = (int) (Math.random() * 255);

 Color color = new Color(a, b, c);

 DataInputStream dis = myQQClient.getDis();
 TextArea textArea = myQQClient.getOldTextArea();
 textArea.setForeground(color);

 try {
  while (myQQClient.isRunnable()) {

  info = dis.readUTF();
  textArea.append(info + "\n");
  }
 } catch (IOException e) {
  //e.printStackTrace();//有错误
 }
}
}

Tags:大学 JAVA 实验

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接