100个Java经典例子(41-50)初学者的利器高手的宝典JavaSE
- package test41;
- import java.io.*;
- /**
- * Title: 运行系统命令
- * Description:运行一个系统的命令,演示使用Runtime类。
- * Filename: CmdExec.java
- */
- public class CmdExec {
- /**
- *方法说明:构造器,运行系统命令
- *输入参数:String cmdline 命令字符
- *返回类型:
- */
- public CmdExec(String cmdline) {
- try {
- String line;
- //运行系统命令
- Process p = Runtime.getRuntime().exec(cmdline);
- //使用缓存输入流获取屏幕输出。
- BufferedReader input =
- new BufferedReader
- (new InputStreamReader(p.getInputStream()));
- //读取屏幕输出
- while ((line = input.readLine()) != null) {
- System.out.println(“java print:”+line);
- }
- //关闭输入流
- input.close();
- }
- catch (Exception err) {
- err.printStackTrace();
- }
- }
- /**
- *方法说明:主方法
- *输入参数:
- *返回类型:
- */
- public static void main(String argv[]) {
- new CmdExec(“myprog.bat”);
- }
- }
- package test43;
- import java.io.*;
- import java.net.*;
- /**
- * Title: 简单服务器客户端
- * Description: 本程序是一个简单的客户端,用来和服务器连接
- * Filename: SampleClient.java
- */
- public class SampleClient {
- public static void main(String[] arges) {
- try {
- // 获取一个IP。null表示本机
- InetAddress addr = InetAddress.getByName(null);
- // 打开8888端口,与服务器建立连接
- Socket sk = new Socket(addr, 8888);
- // 缓存输入
- BufferedReader in = new BufferedReader(new InputStreamReader(sk
- .getInputStream()));
- // 缓存输出
- PrintWriter out = new PrintWriter(new BufferedWriter(
- new OutputStreamWriter(sk.getOutputStream())), true);
- // 向服务器发送信息
- out.println(“你好!”);
- // 接收服务器信息
- System.out.println(in.readLine());
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- }
- package test43;
- import java.net.*;
- import java.io.*;
- /**
- * Title: 简单服务器服务端
- * Description: 这是一个简单的服务器端程序
- * Filename: SampleServer.java
- */
- public class SampleServer {
- public static void main(String[] arges) {
- try {
- int port = 8888;
- // 使用8888端口创建一个ServerSocket
- ServerSocket mySocket = new ServerSocket(port);
- // 等待监听是否有客户端连接
- Socket sk = mySocket.accept();
- // 输入缓存
- BufferedReader in = new BufferedReader(new InputStreamReader(sk
- .getInputStream()));
- // 输出缓存
- PrintWriter out = new PrintWriter(new BufferedWriter(
- new OutputStreamWriter(sk.getOutputStream())), true);
- // 打印接收到的客户端发送过来的信息
- System.out.println(“客户端信息:” + in.readLine());
- // 向客户端回信息
- out.println(“你好,我是服务器。我使用的端口号: ” + port);
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- }
- package test44;
- // 文件名:moreServer.java
- import java.io.*;
- import java.net.*;
- /**
- * Title: 多线程服务器
- * Description: 本实例使用多线程实现多服务功能。
- * Filename:
- */
- class moreServer
- {
- public static void main (String [] args) throws IOException
- {
- System.out.println (“Server starting…n”);
- //使用8000端口提供服务
- ServerSocket server = new ServerSocket (8000);
- while (true)
- {
- //阻塞,直到有客户连接
- Socket sk = server.accept ();
- System.out.println (“Accepting Connection…n”);
- //启动服务线程
- new ServerThread (sk).start ();
- }
- }
- }
- //使用线程,为多个客户端服务
- class ServerThread extends Thread
- {
- private Socket sk;
- ServerThread (Socket sk)
- {
- this.sk = sk;
- }
- //线程运行实体
- public void run ()
- {
- BufferedReader in = null;
- PrintWriter out = null;
- try{
- InputStreamReader isr;
- isr = new InputStreamReader (sk.getInputStream ());
- in = new BufferedReader (isr);
- out = new PrintWriter (
- new BufferedWriter(
- new OutputStreamWriter(
- sk.getOutputStream ())), true);
- while(true){
- //接收来自客户端的请求,根据不同的命令返回不同的信息。
- String cmd = in.readLine ();
- System.out.println(cmd);
- if (cmd == null)
- break;
- cmd = cmd.toUpperCase ();
- if (cmd.startsWith (“BYE”)){
- out.println (“BYE”);
- break;
- }else{
- out.println (“你好,我是服务器!”);
- }
- }
- }catch (IOException e)
- {
- System.out.println (e.toString ());
- }
- finally
- {
- System.out.println (“Closing Connection…n”);
- //最后释放资源
- try{
- if (in != null)
- in.close ();
- if (out != null)
- out.close ();
- if (sk != null)
- sk.close ();
- }
- catch (IOException e)
- {
- System.out.println(“close err”+e);
- }
- }
- }
- }
- package test44;
- //文件名:SocketClient.java
- import java.io.*;
- import java.net.*;
- class SocketThreadClient extends Thread {
- public static int count = 0;
- // 构造器,实现服务
- public SocketThreadClient(InetAddress addr) {
- count++;
- BufferedReader in = null;
- PrintWriter out = null;
- Socket sk = null;
- try {
- // 使用8000端口
- sk = new Socket(addr, 8000);
- InputStreamReader isr;
- isr = new InputStreamReader(sk.getInputStream());
- in = new BufferedReader(isr);
- // 建立输出
- out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk
- .getOutputStream())), true);
- // 向服务器发送请求
- System.out.println(“count:” + count);
- out.println(“Hello”);
- System.out.println(in.readLine());
- out.println(“BYE”);
- System.out.println(in.readLine());
- } catch (IOException e) {
- System.out.println(e.toString());
- } finally {
- out.println(“END”);
- // 释放资源
- try {
- if (in != null)
- in.close();
- if (out != null)
- out.close();
- if (sk != null)
- sk.close();
- } catch (IOException e) {
- }
- }
- }
- }
- // 客户端
- public class SocketClient {
- @SuppressWarnings(“static-access”)
- public static void main(String[] args) throws IOException,
- InterruptedException {
- InetAddress addr = InetAddress.getByName(null);
- for (int i = 0; i < 10; i++)
- new SocketThreadClient(addr);
- Thread.currentThread().sleep(1000);
- }
- }
- package test45;
- import java.net.*;
- import java.io.*;
- /**
- * Title: 使用SMTP发送邮件
- * Description: 本实例通过使用socket方式,根据SMTP协议发送邮件
- * Copyright: Copyright (c) 2003
- * Filename: sendSMTPMail.java
- */
- public class sendSMTPMail {
- /**
- *方法说明:主方法
- *输入参数:1。服务器ip;2。对方邮件地址
- *返回类型:
- */
- public static void main(String[] arges) {
- if (arges.length != 2) {
- System.out.println(“use java sendSMTPMail hostname | mail to”);
- return;
- }
- sendSMTPMail t = new sendSMTPMail();
- t.sendMail(arges[0], arges[1]);
- }
- /**
- *方法说明:发送邮件
- *输入参数:String mailServer 邮件接收服务器
- *输入参数:String recipient 接收邮件的地址
- *返回类型:
- */
- public void sendMail(String mailServer, String recipient) {
- try {
- // 有Socket打开25端口
- Socket s = new Socket(mailServer, 25);
- // 缓存输入和输出
- BufferedReader in = new BufferedReader(new InputStreamReader(s
- .getInputStream(), “8859_1”));
- BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s
- .getOutputStream(), “8859_1”));
- // 发出“HELO”命令,表示对服务器的问候
- send(in, out, “HELO theWorld”);
- // 告诉服务器我的邮件地址,有些服务器要校验这个地址
- send(in, out, “MAIL FROM: <213@qq.com>”);
- // 使用“RCPT TO”命令告诉服务器解释邮件的邮件地址
- send(in, out, “RCPT TO: ” + recipient);
- // 发送一个“DATA”表示下面将是邮件主体
- send(in, out, “DATA”);
- // 使用Subject命令标注邮件主题
- send(out, “Subject: 这是一个测试程序!”);
- // 使用“From”标注邮件的来源
- send(out, “From: riverwind <213@qq.com>”);
- send(out, “n”);
- // 邮件主体
- send(out, “这是一个使用SMTP协议发送的邮件!如果打扰请删除!”);
- send(out, “n.n”);
- // 发送“QUIT”端口邮件的通讯
- send(in, out, “QUIT”);
- s.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- *方法说明:发送信息,并接收回信
- *输入参数:
- *返回类型:
- */
- public void send(BufferedReader in, BufferedWriter out, String s) {
- try {
- out.write(s + “n”);
- out.flush();
- System.out.println(s);
- s = in.readLine();
- System.out.println(s);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- *方法说明:重载方法。向socket写入信息
- *输入参数:BufferedWriter out 输出缓冲器
- *输入参数:String s 写入的信息
- *返回类型:
- */
- public void send(BufferedWriter out, String s) {
- try {
- out.write(s + “n”);
- out.flush();
- System.out.println(s);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- package test46;
- import java.io.*;
- import java.net.*;
- /**
- * Title: SMTP协议接收邮件
- * Description: 通过Socket连接POP3服务器,使用SMTP协议接收邮件服务器中的邮件
- * Filename:
- */
- class POP3Demo
- {
- /**
- *方法说明:主方法,接收用户输入
- *输入参数:
- *返回类型:
- */
- @SuppressWarnings(“static-access”)
- public static void main(String[] args){
- if(args.length!=3){
- System.out.println(“USE: java POP3Demo mailhost user password”);
- }
- new POP3Demo().receive(args[0],args[1],args[2]);
- }
- /**
- *方法说明:接收邮件
- *输入参数:String popServer 服务器地址
- *输入参数:String popUser 邮箱用户名
- *输入参数:String popPassword 邮箱密码
- *返回类型:
- */
- public static void receive (String popServer, String popUser, String popPassword)
- {
- String POP3Server = popServer;
- int POP3Port = 110;
- Socket client = null;
- try
- {
- // 创建一个连接到POP3服务程序的套接字。
- client = new Socket (POP3Server, POP3Port);
- //创建一个BufferedReader对象,以便从套接字读取输出。
- InputStream is = client.getInputStream ();
- BufferedReader sockin;
- sockin = new BufferedReader (new InputStreamReader (is));
- //创建一个PrintWriter对象,以便向套接字写入内容。
- OutputStream os = client.getOutputStream ();
- PrintWriter sockout;
- sockout = new PrintWriter (os, true); // true for auto-flush
- // 显示POP3握手信息。
- System.out.println (“S:” + sockin.readLine ());
- /*– 与POP3服务器握手过程 –*/
- System.out.print (“C:”);
- String cmd = “user “+popUser;
- // 将用户名发送到POP3服务程序。
- System.out.println (cmd);
- sockout.println (cmd);
- // 读取POP3服务程序的回应消息。
- String reply = sockin.readLine ();
- System.out.println (“S:” + reply);
- System.out.print (“C:”);
- cmd = “pass “;
- // 将密码发送到POP3服务程序。
- System.out.println(cmd+”*********”);
- sockout.println (cmd+popPassword);
- // 读取POP3服务程序的回应消息。
- reply = sockin.readLine ();
- System.out.println (“S:” + reply);
- System.out.print (“C:”);
- cmd = “stat”;
- // 获取邮件数据。
- System.out.println(cmd);
- sockout.println (cmd);
- // 读取POP3服务程序的回应消息。
- reply = sockin.readLine ();
- System.out.println (“S:” + reply);
- if(reply==null) return;
- System.out.print (“C:”);
- cmd = “retr 1”;
- // 将接收第一丰邮件命令发送到POP3服务程序。
- System.out.println(cmd);
- sockout.println (cmd);
- // 输入了RETR命令并且返回了成功的回应码,持续从套接字读取输出,
- // 直到遇到<CRLF>.<CRLF>。这时从套接字读出的输出就是邮件的内容。
- if (cmd.toLowerCase ().startsWith (“retr”) &&
- reply.charAt (0) == ‘+’)
- do
- {
- reply = sockin.readLine ();
- System.out.println (“S:” + reply);
- if (reply != null && reply.length () > 0)
- if (reply.charAt (0) == ‘.’)
- break;
- }
- while (true);
- cmd = “quit”;
- // 将命令发送到POP3服务程序。
- System.out.print (cmd);
- sockout.println (cmd);
- }
- catch (IOException e)
- {
- System.out.println (e.toString ());
- }
- finally
- {
- try
- { if (client != null)
- client.close ();
- }
- catch (IOException e)
- {
- }
- }
- }
- }
- package test47;
- import java.util.*;
- import javax.mail.*;
- import javax.mail.internet.*;
- import javax.activation.*;
- /**
- * Title: 使用javamail发送邮件 Description: 演示如何使用javamail包发送电子邮件。这个实例可发送多附件 Filename:
- * Mail.java
- */
- public class Mail {
- String to = “”;// 收件人
- String from = “”;// 发件人
- String host = “”;// smtp主机
- String username = “”;
- String password = “”;
- String filename = “”;// 附件文件名
- String subject = “”;// 邮件主题
- String content = “”;// 邮件正文
- @SuppressWarnings(“unchecked”)
- Vector file = new Vector();// 附件文件集合
- /**
- *方法说明:默认构造器 输入参数: 返回类型:
- */
- public Mail() {
- }
- /**
- *方法说明:构造器,提供直接的参数传入 输入参数: 返回类型:
- */
- public Mail(String to, String from, String smtpServer, String username,
- String password, String subject, String content) {
- this.to = to;
- this.from = from;
- this.host = smtpServer;
- this.username = username;
- this.password = password;
- this.subject = subject;
- this.content = content;
- }
- /**
- *方法说明:设置邮件服务器地址 输入参数:String host 邮件服务器地址名称 返回类型:
- */
- public void setHost(String host) {
- this.host = host;
- }
- /**
- *方法说明:设置登录服务器校验密码 输入参数: 返回类型:
- */
- public void setPassWord(String pwd) {
- this.password = pwd;
- }
- /**
- *方法说明:设置登录服务器校验用户 输入参数: 返回类型:
- */
- public void setUserName(String usn) {
- this.username = usn;
- }
- /**
- *方法说明:设置邮件发送目的邮箱 输入参数: 返回类型:
- */
- public void setTo(String to) {
- this.to = to;
- }
- /**
- *方法说明:设置邮件发送源邮箱 输入参数: 返回类型:
- */
- public void setFrom(String from) {
- this.from = from;
- }
- /**
- *方法说明:设置邮件主题 输入参数: 返回类型:
- */
- public void setSubject(String subject) {
- this.subject = subject;
- }
- /**
- *方法说明:设置邮件内容 输入参数: 返回类型:
- */
- public void setContent(String content) {
- this.content = content;
- }
- /**
- *方法说明:把主题转换为中文 输入参数:String strText 返回类型:
- */
- public String transferChinese(String strText) {
- try {
- strText = MimeUtility.encodeText(new String(strText.getBytes(),
- “GB2312”), “GB2312”, “B”);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return strText;
- }
- /**
- *方法说明:往附件组合中添加附件 输入参数: 返回类型:
- */
- public void attachfile(String fname) {
- file.addElement(fname);
- }
- /**
- *方法说明:发送邮件 输入参数: 返回类型:boolean 成功为true,反之为false
- */
- public boolean sendMail() {
- // 构造mail session
- Properties props = System.getProperties();
- props.put(“mail.smtp.host”, host);
- props.put(“mail.smtp.auth”, “true”);
- Session session = Session.getDefaultInstance(props,
- new Authenticator() {
- public PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
- });
- try {
- // 构造MimeMessage 并设定基本的值
- MimeMessage msg = new MimeMessage(session);
- msg.setFrom(new InternetAddress(from));
- InternetAddress[] address = { new InternetAddress(to) };
- msg.setRecipients(Message.RecipientType.TO, address);
- subject = transferChinese(subject);
- msg.setSubject(subject);
- // 构造Multipart
- Multipart mp = new MimeMultipart();
- // 向Multipart添加正文
- MimeBodyPart mbpContent = new MimeBodyPart();
- mbpContent.setText(content);
- // 向MimeMessage添加(Multipart代表正文)
- mp.addBodyPart(mbpContent);
- // 向Multipart添加附件
- Enumeration efile = file.elements();
- while (efile.hasMoreElements()) {
- MimeBodyPart mbpFile = new MimeBodyPart();
- filename = efile.nextElement().toString();
- FileDataSource fds = new FileDataSource(filename);
- mbpFile.setDataHandler(new DataHandler(fds));
- mbpFile.setFileName(fds.getName());
- // 向MimeMessage添加(Multipart代表附件)
- mp.addBodyPart(mbpFile);
- }
- file.removeAllElements();
- // 向Multipart添加MimeMessage
- msg.setContent(mp);
- msg.setSentDate(new Date());
- // 发送邮件
- Transport.send(msg);
- } catch (MessagingException mex) {
- mex.printStackTrace();
- Exception ex = null;
- if ((ex = mex.getNextException()) != null) {
- ex.printStackTrace();
- }
- return false;
- }
- return true;
- }
- /**
- *方法说明:主方法,用于测试 输入参数: 返回类型:
- */
- public static void main(String[] args) {
- Mail sendmail = new Mail();
- sendmail.setHost(“smtp.sohu.com”);
- sendmail.setUserName(“du_jiang”);
- sendmail.setPassWord(“31415926”);
- sendmail.setTo(“dujiang@sricnet.com”);
- sendmail.setFrom(“du_jiang@sohu.com”);
- sendmail.setSubject(“你好,这是测试!”);
- sendmail.setContent(“你好这是一个带多附件的测试!”);
- // Mail sendmail = new
- // Mail(“dujiang@sricnet.com”,”du_jiang@sohu.com”,”smtp.sohu.com”,”du_jiang”,”31415926″,”你好”,”胃,你好吗?”);
- sendmail.attachfile(“c:\test.txt”);
- sendmail.attachfile(“DND.jar”);
- sendmail.sendMail();
- }
- }// end
- package test48;
- import javax.mail.*;
- import javax.mail.internet.*;
- import java.util.*;
- import java.io.*;
- /**
- * Title: 使用JavaMail接收邮件
- * Description: 实例JavaMail包接收邮件,本实例没有实现接收邮件的附件。
- * Filename: POPMail.java
- */
- public class POPMail{
- /**
- *方法说明:主方法,接收用户输入的邮箱服务器、用户名和密码
- *输入参数:
- *返回类型:
- */
- public static void main(String args[]){
- try{
- String popServer=args[0];
- String popUser=args[1];
- String popPassword=args[2];
- receive(popServer, popUser, popPassword);
- }catch (Exception ex){
- System.out.println(“Usage: java com.lotontech.mail.POPMail”+” popServer popUser popPassword”);
- }
- System.exit(0);
- }
- /**
- *方法说明:接收邮件信息
- *输入参数:
- *返回类型:
- */
- public static void receive(String popServer, String popUser, String popPassword){
- Store store=null;
- Folder folder=null;
- try{
- //获取默认会话
- Properties props = System.getProperties();
- Session session = Session.getDefaultInstance(props, null);
- //使用POP3会话机制,连接服务器
- store = session.getStore(“pop3”);
- store.connect(popServer, popUser, popPassword);
- //获取默认文件夹
- folder = store.getDefaultFolder();
- if (folder == null) throw new Exception(“No default folder”);
- //如果是收件箱
- folder = folder.getFolder(“INBOX”);
- if (folder == null) throw new Exception(“No POP3 INBOX”);
- //使用只读方式打开收件箱
- folder.open(Folder.READ_ONLY);
- //得到文件夹信息,获取邮件列表
- Message[] msgs = folder.getMessages();
- for (int msgNum = 0; msgNum < msgs.length; msgNum++){
- printMessage(msgs[msgNum]);
- }
- }catch (Exception ex){
- ex.printStackTrace();
- }
- finally{
- //释放资源
- try{
- if (folder!=null) folder.close(false);
- if (store!=null) store.close();
- }catch (Exception ex2) {
- ex2.printStackTrace();
- }
- }
- }
- /**
- *方法说明:打印邮件信息
- *输入参数:Message message 信息对象
- *返回类型:
- */
- public static void printMessage(Message message){
- try{
- //获得发送邮件地址
- String from=((InternetAddress)message.getFrom()[0]).getPersonal();
- if (from==null) from=((InternetAddress)message.getFrom()[0]).getAddress();
- System.out.println(“FROM: “+from);
- //获取主题
- String subject=message.getSubject();
- System.out.println(“SUBJECT: “+subject);
- //获取信息对象
- Part messagePart=message;
- Object content=messagePart.getContent();
- //附件
- if (content instanceof Multipart){
- messagePart=((Multipart)content).getBodyPart(0);
- System.out.println(“[ Multipart Message ]”);
- }
- //获取content类型
- String contentType=messagePart.getContentType();
- //如果邮件内容是纯文本或者是HTML,那么打印出信息
- System.out.println(“CONTENT:”+contentType);
- if (contentType.startsWith(“text/plain”)||
- contentType.startsWith(“text/html”)){
- InputStream is = messagePart.getInputStream();
- BufferedReader reader=new BufferedReader(new InputStreamReader(is));
- String thisLine=reader.readLine();
- while (thisLine!=null){
- System.out.println(thisLine);
- thisLine=reader.readLine();
- }
- }
- System.out.println(“————– END —————“);
- }catch (Exception ex){
- ex.printStackTrace();
- }
- }
- }
- package test49;
- import java.io.*;
- import java.net.*;
- /**
- * Title: 获取一个URL文本
- * Description: 通过使用URL类,构造一个输入对象,并读取其内容。
- * Filename: getURL.java
- */
- public class getURL{
- public static void main(String[] arg){
- if(arg.length!=1){
- System.out.println(“USE java getURL url”);
- return;
- }
- new getURL(arg[0]);
- }
- /**
- *方法说明:构造器
- *输入参数:String URL 互联网的网页地址。
- *返回类型:
- */
- public getURL(String URL){
- try {
- //创建一个URL对象
- URL url = new URL(URL);
- //读取从服务器返回的所有文本
- BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
- String str;
- while ((str = in.readLine()) != null) {
- //这里对文本出来
- display(str);
- }
- in.close();
- } catch (MalformedURLException e) {
- } catch (IOException e) {
- }
- }
- /**
- *方法说明:显示信息
- *输入参数:
- *返回类型:
- */
- private void display(String s){
- if(s!=null)
- System.out.println(s);
- }
- }
- package test50;
- import java.io.*;
- /**
- * Title: 客户请求分析
- * Description: 获取客户的HTTP请求,分析客户所需要的文件
- * Filename: Request.java
- */
- public class Request{
- InputStream in = null;
- /**
- *方法说明:构造器,获得输入流。这时客户的请求数据。
- *输入参数:
- *返回类型:
- */
- public Request(InputStream input){
- this.in = input;
- }
- /**
- *方法说明:解析客户的请求
- *输入参数:
- *返回类型:String 请求文件字符
- */
- public String parse() {
- //从Socket读取一组数据
- StringBuffer requestStr = new StringBuffer(2048);
- int i;
- byte[] buffer = new byte[2048];
- try {
- i = in.read(buffer);
- }
- catch (IOException e) {
- e.printStackTrace();
- i = -1;
- }
- for (int j=0; j<i; j++) {
- requestStr.append((char) buffer[j]);
- }
- System.out.print(requestStr.toString());
- return getUri(requestStr.toString());
- }
- /**
- *方法说明:获取URI字符
- *输入参数:String requestString 请求字符
- *返回类型:String URI信息字符
- */
- private String getUri(String requestString) {
- int index1, index2;
- index1 = requestString.indexOf(‘ ‘);
- if (index1 != -1) {
- index2 = requestString.indexOf(‘ ‘, index1 + 1);
- if (index2 > index1)
- return requestString.substring(index1 + 1, index2);
- }
- return null;
- }
- }
- package test50;
- import java.io.*;
- /**
- * Title: 发现HTTP内容和文件内容
- * Description: 获得用户请求后将用户需要的文件读出,添加上HTTP应答头。发送给客户端。
- * Filename: Response.java
- */
- public class Response{
- OutputStream out = null;
- /**
- *方法说明:发送信息
- *输入参数:String ref 请求的文件名
- *返回类型:
- */
- @SuppressWarnings(“deprecation”)
- public void Send(String ref) throws IOException {
- byte[] bytes = new byte[2048];
- FileInputStream fis = null;
- try {
- //构造文件
- File file = new File(WebServer.WEBROOT, ref);
- if (file.exists()) {
- //构造输入文件流
- fis = new FileInputStream(file);
- int ch = fis.read(bytes, 0, 2048);
- //读取文件
- String sBody = new String(bytes,0);
- //构造输出信息
- String sendMessage = “HTTP/1.1 200 OKrn” +
- “Content-Type: text/htmlrn” +
- “Content-Length: “+ch+”rn” +
- “rn” +sBody;
- //输出文件
- out.write(sendMessage.getBytes());
- }else {
- // 找不到文件
- String errorMessage = “HTTP/1.1 404 File Not Foundrn” +
- “Content-Type: text/htmlrn” +
- “Content-Length: 23rn” +
- “rn” +
- “<h1>File Not Found</h1>”;
- out.write(errorMessage.getBytes());
- }
- }
- catch (Exception e) {
- // 如不能实例化File对象,抛出异常。
- System.out.println(e.toString() );
- }
- finally {
- if (fis != null)
- fis.close();
- }
- }
- /**
- *方法说明:构造器,获取输出流
- *输入参数:
- *返回类型:
- */
- public Response(OutputStream output) {
- this.out = output;
- }
- }
- package test50;
- import java.io.*;
- import java.net.*;
- /**
- * Title: WEB服务器
- * Description: 使用Socket创建一个WEB服务器,本程序是多线程系统以提高反应速度。
- * Filename: WebServer.java
- */
- class WebServer
- {
- public static String WEBROOT = “”;//默认目录
- public static String defaultPage = “index.htm”;//默认文件
- public static void main (String [] args) throws IOException
- {//使用输入的方式通知服务默认目录位置,可用./root表示。
- if(args.length!=1){
- System.out.println(“USE: java WebServer ./rootdir”);
- return;
- }else{
- WEBROOT = args[0];
- }
- System.out.println (“Server starting…n”);
- //使用8000端口提供服务
- ServerSocket server = new ServerSocket (8000);
- while (true)
- {
- //阻塞,直到有客户连接
- Socket sk = server.accept ();
- System.out.println (“Accepting Connection…n”);
- //启动服务线程
- new WebThread (sk).start ();
- }
- }
- }
- /**
- * Title: 服务子线程
- * Description: 使用线程,为多个客户端服务
- * Filename:
- */
- class WebThread extends Thread
- {
- private Socket sk;
- WebThread (Socket sk)
- {
- this.sk = sk;
- }
- /**
- *方法说明:线程体
- *输入参数:
- *返回类型:
- */
- public void run ()
- {
- InputStream in = null;
- OutputStream out = null;
- try{
- in = sk.getInputStream();
- out = sk.getOutputStream();
- //接收来自客户端的请求。
- Request rq = new Request(in);
- //解析客户请求
- String sURL = rq.parse();
- System.out.println(“sURL=”+sURL);
- if(sURL.equals(“/”)) sURL = WebServer.defaultPage;
- Response rp = new Response(out);
- rp.Send(sURL);
- }catch (IOException e)
- {
- System.out.println (e.toString ());
- }
- finally
- {
- System.out.println (“Closing Connection…n”);
- //最后释放资源
- try{
- if (in != null)
- in.close ();
- if (out != null)
- out.close ();
- if (sk != null)
- sk.close ();
- }
- catch (IOException e)
- {
- }
- }
- }
- }