import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
import javax.microedition.io.StreamConnection;
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.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class Server extends MIDlet implements CommandListener {
private DataInputStream dis=null;
private DataOutputStream dos=null;
private ServerSocketConnection ssc=null;
//private StreamConnection sc=null;
private SocketConnection sc=null;
private TextField msg=null;
private Form frm=null;
private Command cmdSend=null;
private StringItem imsg=null;
protected void startApp() throws MIDletStateChangeException {
frm=new Form("服务器");
cmdSend=new Command("发送",Command.OK,1);
msg=new TextField("请输入你的信息","",255,TextField.ANY);
frm.append(msg);
frm.addCommand(cmdSend);
frm.setCommandListener(this);
Display.getDisplay(this).setCurrent(frm);
try {
ssc=(ServerSocketConnection)Connector.open("socket://:9999");
sc=(SocketConnection)ssc.acceptAndOpen();
dis=sc.openDataInputStream();
dos=sc.openDataOutputStream();
Chat chat=new Chat();
chat.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void commandAction(Command c, Displayable d) {
if(c==cmdSend)
{
try {
dos.writeUTF(msg.getString()+"\n");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage()+"\n");
}
msg.setString("");
}
}
protected void destroyApp(boolean b) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
class Chat extends Thread
{
public void run()
{
while(true)
{
try {
imsg=new StringItem( dis.readUTF(),"");
frm.insert(1, imsg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}