日期:2014-05-17  浏览次数:20684 次

jsp进行udp通信
现在的问题是:
1.当我打开jsp的页面时候,就发送一个udp广播包。对方捕捉到后向我发送数据,我解析后显示出来。
2.当我点击jsp页面中的按钮的时候,发送一个udp包,进行关灯开灯操作。
请问如何操作?
------解决方案--------------------
你到底是想在服务器端发包,还是想在客户端?
如果是在服务器端,直接在 jsp 里嵌入 java 代码即可,jsp 引擎会帮你解析成 servlet,后者由 servlet 引擎在服务器端执行,于是你的 java 代码就执行了。
如果实在客户端,可以调用 applet,用 jsp 调用 applet 类里的具体方法代码来发 udp包。
这里有个 java 进行 udp 发包的例子,希望可以帮到你:
import java.net.*;
import java.io.*;

/**
 * UDPSender is an implementation of the Sender interface, using UDP as the transport protocol.
 * The object is bound to a specified receiver host and port when created, and is able to 
 * send the contents of a file to this receiver.
 *
 * @author Alex Andersen (alex@daimi.au.dk)
 */
public class UDPSender implements Sender{
    private File theFile;
    private FileInputStream fileReader;
    private DatagramSocket s;
    private int fileLength, currentPos, bytesRead, toPort;
    private byte[]  msg, buffer;
    private String toHost,initReply;
    private InetAddress toAddress;


    /**
     * Class constructor.
     * Creates a new UDPSender object capable of sending a file to the specified address and port.
     *
     * @param address  the address of the receiving host
     * @param port    the listening port on the receiving host
     */
    public UDPSender(InetAddress address, int port) throws IOException{
toPort = port;
toAddress = address;
msg = new byte[8192];
buffer = new byte[8192];
s = new DatagramSocket();
        s.connect(toAddress, toPort);
    }
    

    /**
     * Sends a file to the bound host.
     * Reads the contents of the specified file, and sends it via UDP to the host 
     * and port specified at when the object was created.
     *
     * @param theFile  the file to send
     */
    public void sendFile(File theFile) throws IOException{
// Init stuff
fileReader = new FileInputStream(theFile);
fileLength = fileReader.available();

System.