socketclient.java

来自「Java手机程序开发-SocketClient1」· Java 代码 · 共 69 行

JAVA
69
字号
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;

public class SocketClient extends MIDlet implements CommandListener{

	Display display;
	Form result;
	String serverURL = "socket://127.0.0.1:5678";
	String message;
	Command exitCmd;
	Command connectCmd;

	public SocketClient(){
		display = Display.getDisplay(this);
		result = new Form("取的信息");
		exitCmd = new Command("退出", Command.EXIT, 1);
		connectCmd = new Command("联机", Command.SCREEN, 1);
		result.addCommand(exitCmd);
		result.addCommand(connectCmd);
		result.setCommandListener(this);
	}

	public void startApp(){
		display.setCurrent(result);
	}

	public void pauseApp(){
	}

	public void destroyApp(boolean conditional){
	}

	public void commandAction(Command c, Displayable d){
		if( c == exitCmd){
			destroyApp(true);
			notifyDestroyed();
		}
		else if (c == connectCmd){
			try{
				connect(serverURL);
			}
			catch(Exception ex){}
		}
	}

	void connect(String url) throws IOException{
		StreamConnection con = (StreamConnection)Connector.open(url);
		InputStream ins = con.openInputStream();
		int data;
		StringBuffer sb = new StringBuffer();
		try{
			while((data = ins.read()) != -1){
				sb.append((char)data);
			}
			message = sb.toString();
			System.out.println(message);
			result.append(message);
			display.setCurrent(result);
		}
		finally{
			if(ins != null)
				ins.close();
			if(con != null)
				con.close();
		}
	}
}

⌨️ 快捷键说明

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