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

📄 clientdemo.java

📁 jBuilderX无线应用开发源代码
💻 JAVA
字号:
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;

public class ClientDemo extends MIDlet implements CommandListener,Runnable {
    private static Display display;
    private Form f;
    private StringItem si,sd;
	private SocketConnection sc;
	private InputStream is;

    private Command exitCommand = new Command("Exit", Command.EXIT, 1);
    private Command startCommand = new Command("GetTime", Command.ITEM, 1);

   public ClientDemo() {      
      f = new Form("Time Demo");
      si = new StringItem("Select GetTime to get the current Time!", "");
      f.append(si);
	  sd = new StringItem("Time:" , "");
	  f.append(sd);
      f.addCommand(exitCommand);
      f.addCommand(startCommand);
      f.setCommandListener(this);      
   }

	public void startApp() {
		display = Display.getDisplay(this);
		display.setCurrent(f);
	}

	public void pauseApp() {
	}

	public void destroyApp(boolean unconditional) {
	}

	public void commandAction(Command c, Displayable s) {
		if (c == exitCommand) {
			destroyApp(true);
			notifyDestroyed();
		} 
		else if (c == startCommand) {
			//启动一个新的线程来执行网络连接操作
			Thread t = new Thread(this);
			t.start();
		}
		else if (c == Alert.DISMISS_COMMAND) {
			destroyApp(true);
			notifyDestroyed();
		}
	}

	public void run() {
		try {
			//打开Socket连接
			sc = (SocketConnection)Connector.open("socket://localhost:123");
			//获得Socket连接的输入流
			is = sc.openInputStream();
			//读取服务器发送的数据
			StringBuffer sb = new StringBuffer();
			int c = 0;
			while (((c = is.read()) != '\n') && (c != -1)) {
				sb.append((char) c);
			}
			//显示读到的数据
			sd.setText(sb.toString());
		} 
		catch(IOException e) {
			e.printStackTrace();
			Alert a = new Alert("TimeClient", "Cannot connect to server. Ping the server to make sure it is running...", null, AlertType.ERROR);
			a.setTimeout(Alert.FOREVER);
			a.setCommandListener(this);
			display.setCurrent(a);
		} 
		finally {
			try {
				//关闭输入流
				if(is != null) {
					is.close();
				}
				//关闭连接
				if(sc != null) {
					sc.close();
				}
			} 
			catch(IOException e) {
				e.printStackTrace();
			}
		}
	}		
}

⌨️ 快捷键说明

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