随笔-22  评论-6  文章-17  trackbacks-0
 

//服务器代码
/********************************Main******************************/

import java.io.*;
import java.net.*;
import java.util.*;
public class ServerMain{
 public static Vector socketVector=new Vector();
 public static void main(String[] args) throws IOException{
          System.out.println("服务器启动........");
  ServerSocket s = new ServerSocket(5000);
  while(true){
   Socket soc = s.accept();
   SocketThread st=new SocketThread(soc);
   socketVector.addElement(st);
   st.start();
  }
 }
 public static void sendEveryone(String msg){
                Object object=null;
  int len=socketVector.size();
  for(int i=0;i<len;i++){
                        try {
                          object=socketVector.elementAt(i);
                          SocketThread st = (SocketThread)object;
                          st.sender.send(msg);
                        }
                        catch (Exception ex) {
                          socketVector.removeElement(object);
                        }
  }
 }
        public static void removeObject(Object object){
          socketVector.removeElement(object);
        }
        public static void removeObject(Sender sender) throws Exception{
          int len=socketVector.size();
                for(int i=0;i<len;i++){
                  Object object=socketVector.elementAt(i);
                  SocketThread st = (SocketThread)object;
                  if(st.sender==sender)
                    socketVector.removeElement(object);
                }

        }

}

/*********************************SocketThread **********************/
import java.io.*;
import java.net.*;
import java.util.*;
public class SocketThread implements Runnable{
 public Socket socke;
 public DataInputStream dis;
 public DataOutputStream dos;
 public Sender sender;
        private boolean stop;
        Calendar date;// = Calendar.getInstance(TimeZone.getTimeZone("Asia/ShangHai"));
 public SocketThread(Socket sok){
  socke=sok;
 }
 public void start(){
  Thread t=new Thread(this);
  t.start();
 }
      public void run() {
        try {
          socke.setKeepAlive(true);
          dis = new DataInputStream(socke.getInputStream());
          dos = new DataOutputStream(socke.getOutputStream());
          sender = new Sender(dos);
          while (true) {
            StringBuffer sb = new StringBuffer();
           char c;
           while (((c = dis.readChar()) != '\n') && (c != -1)) {
             sb.append(c);
           }
            if (c == -1) {
              break;
            }
            date = Calendar.getInstance(TimeZone.getTimeZone("Asia/ShangHai"));
            String ljnTime="("+date.get(date.YEAR)+"/"+(date.get(date.MONTH)+1)+"/"+date.get(date.DATE)+" "+date.get(date.HOUR_OF_DAY)+":"+date.get(date.MINUTE)+":"+date.get(date.SECOND)+")";
            String acceptMsg=sb.toString();
            System.out.println(ljnTime+acceptMsg);
            ServerMain.sendEveryone(acceptMsg);
          }
          stop();
         ServerMain.removeObject(this);
        } catch (IOException ioe) {
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
  public void stop() {
   try {
    stop = true;
    if(sender!=null){
      sender.stop1();
    }
    if (dis != null) {
     dis.close();
    }
    if (dos != null) {
     dos.close();
    }
    if (socke != null) {
     socke.close();
    }
   } catch (IOException ioe) {
   }
  }
}
/*********************************************Sender**************************/
import java.io.*;
public class Sender extends Thread {
 private DataOutputStream dos;
 private String message;
 public Sender(DataOutputStream os) {
  this.dos = os;
  start();
 }
 public synchronized void send(String msg) {
  message = msg;
  notify();
 }

 public synchronized void run() {

  while (true) {
   if (message == null) {
    try {
     wait();
    } catch (InterruptedException e) {
    }
   }

   if (message == null) {
    break;
   }

   try {
   dos.writeChars(message);
   dos.writeChars("\r\n");
   } catch (IOException ioe) {
    try {
      ServerMain.removeObject(this);
    }
    catch (Exception ex) {
    }
   }
   message = null;
  }
 }

 public synchronized void stop1() {
  message = null;
  notify();
 }
}
//下面为手机客户端代码

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class ChatClientMIDlet extends MIDlet {
  private static ChatClientMIDlet instance;
  public static ChatForm displayable = new ChatForm();
  /** Constructor */
  public ChatClientMIDlet() {
    instance = this;
  }

  /** Main method */
  public void startApp() {
    Display.getDisplay(this).setCurrent(displayable);
  }

  /** Handle pausing the MIDlet */
  public void pauseApp() {
  }

  /** Handle destroying the MIDlet */
  public void destroyApp(boolean unconditional) {
  }
  public static void setCurrent(Displayable s){
     Display.getDisplay(instance).setCurrent(s);
  }
  /** Quit the MIDlet */
  public static void quitApp() {
    instance.destroyApp(true);
    instance.notifyDestroyed();
    instance = null;
  }

}
/********************************************************ChatForm ************************/
import com.nec.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class ChatForm extends Form implements CommandListener,Runnable {
  public Form mainForm=new Form("聊天室");
  public Command enter=new Command("进入",Command.OK,0);
  public Command send=new Command("发送",Command.OK,1);
  public Command exit=new Command("退出",Command.EXIT,0);
  public DataInputStream dis;
  public DataOutputStream dos;
  public SocketConnection sc;
  public Sender sender;
  public boolean stop;
  public TextField textField=new TextField("请输入昵称:", null, 10, TextField.ANY);
  public TextField info=new TextField("请输入消息:", null,255, TextField.ANY);
  public ChoiceGroup choiceGroup=new ChoiceGroup(null,ChoiceGroup.EXCLUSIVE);
  public String MyName="游客";
  public boolean isCurrent=false;;
  public ChatForm() {
    super("我的聊天室");
    append(textField);
    addCommand(enter);
    mainForm.append(info);
    mainForm.append(choiceGroup);
    choiceGroup.append("www.modia.cn",null);
    setCommandListener(this);
    mainForm.addCommand(send);
    mainForm.addCommand(exit);
    mainForm.setCommandListener(this);
  }
  public void commandAction(Command c, Displayable dis) {
    if(c==enter){
     if(textField.getString().length()==0){
      Alert alert=new  Alert("警告","昵称不能为空!", null, AlertType.WARNING) ;
      alert.setTimeout(3000);
      ChatClientMIDlet.setCurrent(alert);
      return;
     }else
       {
         MyName = textField.getString();
        append("正在进入......");
       }
      Thread t=new Thread(this);
      t.start();
    }else if(c==send){
      if(info.getString().length()==0){
        Alert alert=new  Alert("警告","消息内容不能为空!", null, AlertType.WARNING) ;
        alert.setTimeout(3000);
        ChatClientMIDlet.setCurrent(alert);
        return;
      }
      sender.send(MyName+"说:"+info.getString());
      info.setString("");
    }
    else{
      stop();
      ChatClientMIDlet.quitApp();
    }
  }
  public void run() {
   try {
    sc = (SocketConnection) Connector.open("socket://127.0.0.1:5000");
    sc.setSocketOption(SocketConnection.LINGER, 5);
    dis = new DataInputStream(sc.openInputStream());
    dos = new DataOutputStream(sc.openOutputStream());
    sender = new Sender(dos);
    sender.send("欢迎"+MyName+"进入房间");
    while (true) {
      if(stop) break;
      StringBuffer sb = new StringBuffer();
     char c;
     while (((c = dis.readChar()) != '\n') && (c != -1)) {
        sb.append(c);
      }
     if (c == -1)   break;
     if(!isCurrent){
       ChatClientMIDlet.setCurrent(mainForm);
       isCurrent=true;
     }
     String msg=sb.toString();
     msg=msg.substring(0,msg.length()-2);
     choiceGroup.insert(0,msg,null);
     choiceGroup.setSelectedIndex(0,true);
    }
    stop();
   } catch (ConnectionNotFoundException cnfe) {
   } catch (IOException ioe) {
    if (!stop) {
     ioe.printStackTrace();
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  public void stop() {
    try {
     stop = true;
     if (sender != null) {
      sender.stop1();
     }

     if (dis != null) {
      dis.close();
     }

     if (dos != null) {
      dos.close();
     }

     if (sc != null) {
      sc.close();
     }
    } catch (IOException ioe) {
    }
   }

}
/**************************Sender*********************************/

同上

posted on 2005-11-22 12:54 surffish 阅读(1070) 评论(2)  编辑  收藏

评论:
# re: 手机socket聊天室(server+Client) (来自jsljn272的专栏) 2007-05-19 12:15 | 子夜风
不错,支持哈!
向你学习  回复  更多评论
  
# re: 手机socket聊天室(server+Client) (来自jsljn272的专栏) 2007-06-30 03:08 | didi
是在j2me平台上运行的吗?本人非常感兴趣!能不能加我QQ 124527984  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: