隨筆-22  評論-6  文章-17  trackbacks-0
           

          //服務(wù)器代碼
          /********************************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("服務(wù)器啟動........");
            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("發(fā)送",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(");
              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("警告","消息內(nèi)容不能為空!", 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*********************************/

          同上


          評論:
          # re: 手機socket聊天室(server+Client) (來自jsljn272的專欄) 2007-05-19 12:15 | 子夜風(fēng)
          不錯,支持哈!
          向你學(xué)習(xí)  回復(fù)  更多評論
            
          # re: 手機socket聊天室(server+Client) (來自jsljn272的專欄) 2007-06-30 03:08 | didi
          是在j2me平臺上運行的嗎?本人非常感興趣!能不能加我QQ 124527984  回復(fù)  更多評論
            

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 平泉县| 北辰区| 南京市| 谷城县| 报价| 临泽县| 靖远县| 准格尔旗| 瑞安市| 南召县| 乳山市| 屏南县| 新安县| 新干县| 化德县| 寻甸| 汉源县| 永川市| 青岛市| 阿巴嘎旗| 什邡市| 乌拉特后旗| 青海省| 饶平县| 安泽县| 东方市| 平湖市| 连州市| 邢台县| 东明县| 临桂县| 锡林浩特市| 凭祥市| 嘉义县| 共和县| 乳源| 沐川县| 仲巴县| 四会市| 永德县| 双桥区|