⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udpmidlet.java

📁 在j2me环境下实现udp的通信
💻 JAVA
字号:
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class UDPMIDLet extends MIDlet {
    private static UDPMIDLet instance;
    private UDPScreen displayable = new UDPScreen(this);
	public UDPMIDLet() {
		// TODO Auto-generated constructor stub
		instance = this;
		
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		// TODO Auto-generated method stub

	}

	protected void pauseApp() {
		// TODO Auto-generated method stub

	}

	protected void startApp() throws MIDletStateChangeException {
		// TODO Auto-generated method stub
     Display.getDisplay(this).setCurrent(displayable);	
	}
}

 class UDPScreen extends Form implements CommandListener
 {
	 private UDPMIDLet udpmidlet;
	 public UDPScreen(UDPMIDLet udp)
	 {
		 super("UDP显示");
		 this.udpmidlet = udp;
		 try
		 {
			 setCommandListener(this);
			 addCommand(new Command("连接",Command.OK,1));
		 }
		 catch(Exception e)
		 {e.printStackTrace();}
	 }
	 
	 class UDPConnector implements java.lang.Runnable
	 {
		public void run() {
			connect();
		} 
	 }
	 
	 public void connect()
	 {
		 Datagram revdata,senddata;
		 byte[] s=null;
		 try
		 {
			 UDPDatagramConnection con = (UDPDatagramConnection)
			                             Connector.open("datagram://192.168.0.168:5555");
			 String clientmsg = "Hello Server!";
			 senddata = con.newDatagram(clientmsg.getBytes(), clientmsg.length());
			 con.send(senddata);
			 revdata=con.newDatagram(con.getMaximumLength());
			 con.receive(revdata);
			 con.close();
			 s = revdata.getData(); 
		 }
		 catch(Exception e)
		 {e.printStackTrace();}
		 TextBox input = new TextBox("Server reply:","whatisthis",50000,TextField.ANY);
		 input.setString(new String(s));
		 Display.getDisplay(udpmidlet).setCurrent(input);
		  
	 }
	public void commandAction(Command cmd, Displayable arg1) {
		// TODO Auto-generated method stub
		if(cmd.getCommandType() == Command.OK)
		{
			new java.lang.Thread(new UDPConnector()).start();
		}
	} 
 }












⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -