applet与servlet的网络通信

转自:http://hnzhoujunmei.iteye.com/blog/775143

applet与servlet的网络通信的例子

新建web项目,项目结构如下图: 

applet源码:

View Code
package client;

import java.applet.Applet;
import java.awt.Button;
import java.awt.HeadlessException;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class NetEcho extends Applet implements ActionListener {

    TextField txtOutput;
    Button btnOutput;
    TextArea txtInput;
    Label lblOutput;
    Label lblInput;
    int turnOutput = 0;

    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

        if (txtOutput.getText() == null || txtOutput.getText().equals("")) {
            return;
        }

        try {
            URL url = new URL(
                    "http://localhost:8080/appletServlet/NetEchoServlet"); // 打开连接
            URLConnection con = url.openConnection();
            con.setUseCaches(false); // 不用浏览器缓存
            con.setDoOutput(true);
            con.setDoInput(true);
            // 设置请求消息头
            con.setRequestProperty("Content-type", "application/octet-stream");
            turnOutput += 1;
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();

            DataOutputStream out = new DataOutputStream(byteOut);
            out.writeInt(turnOutput);
            out.writeUTF(txtOutput.getText());
            out.flush();

            byte[] buff = byteOut.toByteArray();
            // 设置请求消息中数据长度
            con.setRequestProperty("Content-length", "" + buff.length);
            DataOutputStream buffout = new DataOutputStream(con
                    .getOutputStream());
            buffout.write(buff); // 将缓冲区中数据发出
            buffout.flush();
            buffout.close();
            // 读取输入
            DataInputStream in = new DataInputStream(con.getInputStream());
            txtInput.append(in.readInt() + ":" + in.readUTF() + "\n");
            in.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public NetEcho() {
        super();
    }

    public void destroy() {
        // Put your code here
    }

    public String getAppletInfo() {
        return "This is my default applet created by Eclipse";
    }

    public void init() {
        // Put your code here
        lblOutput = new Label("发送的数据");
        lblInput = new Label("接收的数据");

        txtOutput = new TextField();
        txtOutput.setColumns(10);

        this.add(lblOutput);
        this.add(txtOutput);
        btnOutput = new Button("发送");
        this.add(btnOutput);
        txtInput = new TextArea("", 20, 30);
        this.add(lblInput);
        this.add(txtInput);
        btnOutput.addActionListener(this);

    }

    public void start() {
        // Put your code here
    }

    public void stop() {
        // Put your code here
    }

}

嵌入applet的html文件

View Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>applet发送至servlet例子</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
    
  </head>
  
  <body>
    
    <applet codebase="." 
            code="client.NetEcho.class" 
            name="NetEcho" 
            width="320" 
            height="240">
      
        
    </applet>
  </body>
</html>

servlet的源码:

 

View Code
package server;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NetEchoServlet extends HttpServlet {

    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
//设置响应头MIME类型
        response.setContentType("application/octet-stream");
        
        DataInputStream in = new DataInputStream(request.getInputStream());
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        
        DataOutputStream out = new DataOutputStream(byteOut);
        
//
        int i = in.readInt();
        String j = in.readUTF();
        
        out.writeInt(i); //写回客户端
        out.writeUTF(j);
        out.flush();
        
        byte[] buff = byteOut.toByteArray();
        response.setContentLength(buff.length);
        
//        取得输出流
        ServletOutputStream httpOut = response.getOutputStream();
        httpOut.write(buff); //发送
        httpOut.close();
    }

}

配置文件:web.xml

View Code
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>NetEchoServlet</servlet-name>
    <servlet-class>server.NetEchoServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>NetEchoServlet</servlet-name>
    <url-pattern>/NetEchoServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

在tomcat中部署后的目录结构:

其中classes目录下的结构:

双击html文件,执行结果如下:

 

posted @ 2013-01-10 22:25  方子格  阅读(371)  评论(0编辑  收藏  举报