chatclientmidlet.java

来自「这是郭克华老师的J2ME视频的源代码」· Java 代码 · 共 77 行

JAVA
77
字号
package example1;

import java.io.DataInputStream;
import java.io.DataOutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import example1.ChatServerMIDlet.ReceiveThread;

public class ChatClientMIDlet extends MIDlet implements CommandListener{
	
	private SocketConnection sc = null;
	private DataInputStream dis = null;
	private DataOutputStream dos = null;
	
	private TextField tfMsg = new TextField("输入聊天信息","",255,TextField.ANY);
	private Command cmdSend = new Command("发送",Command.SCREEN,1);	
	private Form frmChat = new Form("聊天界面");
	private Display display;
	protected void startApp() throws MIDletStateChangeException {
		display = Display.getDisplay(this);
		display.setCurrent(frmChat);
		frmChat.addCommand(cmdSend);
		frmChat.append(tfMsg);
		frmChat.setCommandListener(this);
		
		try{
			sc = (SocketConnection)Connector.open("socket://127.0.0.1:9999");
			dis = sc.openDataInputStream();
			dos = sc.openDataOutputStream();
			new ReceiveThread().start();
		}catch(Exception ex){
			ex.printStackTrace();
		}

	}
	public void commandAction(Command c,Displayable d){
		if(c==cmdSend){
			try{
				dos.writeUTF(tfMsg.getString());
			}catch(Exception ex){}			
		}
	}
	
	class ReceiveThread extends Thread{
		public void run(){
			while(true){
				try{
					String msg = dis.readUTF();
					frmChat.append(msg + "\n");
				}catch(Exception ex){}	
			}
		}
	}
	
	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		// TODO Auto-generated method stub

	}

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

	}


}

⌨️ 快捷键说明

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