import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.*;
import java.util.*;
public class server extends MIDlet implements CommandListener{
private ServerSocketConnection ssc=null;
private SocketConnection sc=null;
private String msg=null;
private TextField tf=new TextField("输入聊天信息", "", 255,TextField.ANY);
private Command cmdSend=new Command("send",Command.OK,1);
private Form f=new Form("聊天室服务端");
private Display disp;
boolean isrec=false;
Vector vc=new Vector();
public server() {
// TODO Auto-generated constructor stub
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
//close();
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
disp=Display.getDisplay(this);
disp.setCurrent(f);
//f.append(tf);
//f.addCommand(cmdSend);
f.setCommandListener(this);
try {
ssc=(ServerSocketConnection)Connector.open("socket://:9999"); //监听9999端口
while(true)
{
sc=(SocketConnection)ssc.acceptAndOpen(); //获得一个客户端的连接
client c=new client(sc); //为这个客户端创建一个线程
c.start(); //启动这个线程
vc.addElement(c);} //将线程添加入容器进行管理
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void commandAction(Command c, Displayable d) {
// TODO Auto-generated method stub
if(c.equals(cmdSend))
{
}
}
class client extends Thread
{
private DataOutputStream dos=null;
private DataInputStream dis=null;
private String name=null;
private SocketConnection sc=null;
client(SocketConnection sc)
{
this.sc=sc;
}
public void run()
{
try {
//sc=(SocketConnection)ssc.acceptAndOpen();
dos=sc.openDataOutputStream();
dis=sc.openDataInputStream();
name=dis.readUTF();
f.append(name+"成功登陆/n");
dos.writeUTF("欢迎 "+name+" 进入聊天室/n");
isrec=true;
while(isrec)
{
try {
msg=dis.readUTF();
f.append(name+":"+msg+"/n");
for(int i=0;i<vc.size();i++) //当一个收到一条信息,就转发给所有客户端
{client c;
c=(client)vc.elementAt(i);
c.dos.writeUTF(name+":"+msg+"/n");}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{close();}
}
} catch (IOException e) {}
}
public void close()
{ try {
sc.close();
dos.close();
dis.close();
ssc.close();
isrec=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
}