⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 switchboardsession.java

📁 J2me实现的MSN Messeger客户端程序。聊天、添加好友、删除好友、阻止好友
💻 JAVA
字号:
/*
 * @(#)SwitchboardSession.java
 *
 * Copyright (c) 2001-2002, JangHo Hwang
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 	1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * 	2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * 	3. Neither the name of the JangHo Hwang nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *    $Id: SwitchboardSession.java,v 2.0 2004/12/21 16:15:08 chenzs Exp $
 */
package vitular.msnp;

//import java.lang.reflect.Method;
//import java.io.CharArrayWriter;
import java.io.IOException;
//import java.util.Collection;
import java.util.Hashtable;

import vitular.msnp.entity.Callback;
import vitular.msnp.entity.MsnFriend;
import vitular.msnp.msg.IncomingMessage;
import vitular.msnp.msg.OutgoingMessage;
import vitular.msnp.msg.MimeMessage;
import vitular.msnp.entity.CallbackListener;
import vitular.msnp.util.BufferedReader;

//import rath.msnm.msg.FileTransferMessage;
//import rath.msnm.ftp.ToSendFile;
//import rath.msnm.ftp.FileMessageProcessor;

/**
 * 中转处理
 * 客户端之间的通讯由中转服务器处理(Switchboard Server).
 * 中转服务器是由Notification Server分配的.和不同客户端通讯可能通过不同Switchboard Server进行连接
 * 应此在一个msn中可能建立多个和Swtichboard Server的连接.
 * <p>Title: MSNP Lib</p>
 * <p>Description: Unija 版Msn协议</p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: Vitular</p>
 * @author ceze
 * @version 1.0
 */
public class SwitchboardSession
    extends AbstractProcessor
    implements CallbackListener {
  private static final String DEFAULT_CONNECT_SERVER =
      "http://gateway.messenger.hotmail.com";
  private static final String DEFAULT_CONNECT_CMD = "Action=open&Server=SB&IP=";
  private static int timeOut = 240000; //4分钟超时
  protected long activeTime;

//	private FileMessageProcessor file = null;

  private String sessionId = null;
  private String cookie = null;
  private Hashtable friendMap = new Hashtable();
  private MsnFriend lastFriend = null;

  public SwitchboardSession(MSNMessenger msn, String targetIp, String sessionId) {
    super(msn, DEFAULT_CONNECT_SERVER, 1);
    setServerName("SB");
    setRequestCommand(DEFAULT_CONNECT_CMD + targetIp);
    setAutoOutSend(true);
    setCallbackListener(this);
    this.sessionId = sessionId;
    //this.file = new FileMessageProcessor(this);
    activeTime = System.currentTimeMillis();
  }

  /**
   * ???? ???? id?? ????? ???·? ????????.
   */
  public String getSessionId() {
    return this.sessionId;
  }

  /**
   * ???? ?????? id?? ????? ???·? ??d???.
   */
  public void setSessionId(String sessionId) {
    this.sessionId = sessionId;
  }

  public String getCookie() {
    return this.cookie;
  }

  public void setCookie(String cookie) {
    this.cookie = cookie;
  }

//  protected void makeConnection() throws IOException {
//    super.makeConnection();
//    //setTimeout(timeout);
//  }

  /**
   * ?? Channel???? ???? ????? ????? ?0??? ???; ???
   * ????; ~????? ?? ?? ????, ??? ????? Timeout8?? millisecond??'?? ??d???.
   *
   * @param  timeout  millisecond??'?? SO_TIMEOUT
   */
//  public void setTimeout(int timeout) {
//    this.timeout = timeout;
//    if (socket != null) {
//      try {
//        socket.setSoTimeout(timeout);
//      }
//      catch (IOException e) {
//        System.err.println("can't assign SO_TIMEOUT value");
//      }
//    }
//  }

  /**
   * ?? Channel???? ???? ????? ????? ?0??? ???; ???
   * ????; ~????? ?? ?? ????, ??? ????? Timeout8?? millisecond??'?? ?????.
   * <p>
   * default?? 180000(3??)8?? ??d??????.
   */
  public int getTimeout() {
    return this.timeOut;
  }

  public void processError(Throwable e) {
    if (msn != null)
      msn.fireConnectFailEvent(msn.ERR_CONNECTION_FAIL, false);
    System.err.println(this.getClass().getName() + ":");
//   e.printStackTrace();
  }

  public void init() throws IOException {
    isProcessInit = true;
    Callback cb = Callback.getInstance(PROCESS_ROSTER_INFO);
    cb.setInfinite();

    OutgoingMessage out = new OutgoingMessage("ANS");
    markTransactionId(out);
    out.add(msn.getLoginName());
    out.add(cookie);
    out.add(sessionId);
    out.setBackProcess(cb);
    sendMessage(out);

  }

  /**
   * ?d ?????? ?? ????? ??????.
   */
  protected void addMsnFriend(MsnFriend friend) {
    friendMap.put(friend.getLoginName(), friend);
    this.lastFriend = friend;
  }

  /**
   * ???? ???? ?? ????? ???? ????? ?????.
   */
  public MsnFriend getMsnFriend() {
    return this.lastFriend;
  }

  /**
   * ????? loginName; ???? ?????? ?? ????? ????????? ?????
   * ??????.
   */
  public boolean isInFriend(String loginName) {
    return friendMap.containsKey(loginName);
  }

  /**
   * ?d loginName; ???? ?????? ?? ??????? f?????.
   */
  protected MsnFriend removeMsnFriend(String loginName) {
    return (MsnFriend) friendMap.remove(loginName);
  }

//  public Collection getMsnFriends() {
//    return friendMap.values();
//  }

  /**
   * 好友列表 Collection -> Hashtable 2004/5/30 ceze
   * @return Hashtable
   */
  public Hashtable getMsnFriends() {
    return friendMap;
  }

  /**
   * ???? ?? ????? ????????? ????? ?? ?????.
   * ??? ???: ?? ??????? f????.
   */
  public int getFriendCount() {
    return friendMap.size();
  }

  /**
   *
   */
  protected void processMimeMessage(IncomingMessage msg, BufferedReader in) throws
      Exception {
    //不采用 CharArrayWriter 2004/5/30 ceze
    //CharArrayWriter caw = new CharArrayWriter(6);

    MimeMessage mime = new MimeMessage( /*msg.get(0), msg.get(1)*/);
    int len = msg.getInt(2);
    int readlen = 0;
    byte[] b = new byte[len];
    int buf;
    while (true) {
      buf = in.read();
      if (buf == -1)
        break;

      byte[] currentBytes = String.valueOf( (char) buf).getBytes("UTF-8");
      System.arraycopy(currentBytes, 0, b, readlen, currentBytes.length);
      readlen += currentBytes.length;

      if (! (readlen < len))
        break;
      //caw.reset();
    }
    String s = new String(b, 0, readlen, "UTF-8");
    mime.parse(s);
    if (Debug.printMime)
      System.out.println(s);

    int kind = mime.getKind();
    switch (kind) {
      case MimeMessage.KIND_TYPING_USER:
        processTypingUser(msg, mime);
        break;
      case MimeMessage.KIND_MESSAGE:
        processInstantMessage(msg, mime);
        break;
      case MimeMessage.KIND_FILE_TRANSFER:

        //文件传输 不处理 2004/5/30 ceze
        //file.processMessage(msg, mime);
        break;
      case MimeMessage.KIND_UNKNOWN:
        break;
    }
  }

  protected void processWhoJoined(IncomingMessage msg) throws Exception {
    String loginName = msg.get(0);
    String friendlyName = msg.get(1);

    MsnFriend friend = new MsnFriend(loginName, friendlyName);
    addMsnFriend(friend);
    msn.fireJoinSessionEvent(this, friend);
  }

  /**
   * Switchboard Server?κ??? notify??? ??????; ó?????.
   */
  public void processNotifyMessage(IncomingMessage msg, BufferedReader in) throws
      Exception {
    String header = msg.getHeader();
    if (header.equals("MSG"))
      processMimeMessage(msg, in);
    else
    if (header.equals("JOI"))
      processWhoJoined(msg);
    else
    if (header.equals("BYE")) {
      String partLoginName = msg.get(0);
      MsnFriend parter = removeMsnFriend(partLoginName);

      if (parter != null)
        msn.firePartSessionEvent(this, parter);
      if (friendMap.size() == 0) {
        isLive = false;
      }
    }

    activeTime = System.currentTimeMillis();
  }

  /**
   * ?????尡 ~???? ?????; ??? ???? ?????.
   */
  public void cleanUp() {
    try {
      close();
    }
    catch (IOException e) {}
    friendMap.clear();
    if (sessionId != null)
      msn.fireSwitchboardSessionEndedEvent(this);
  }

  /**
   * ?? ????; ~?????.
   */
  public void close() throws IOException {
    isLive = false;

    OutgoingMessage out = new OutgoingMessage("OUT");
    sendMessage(out);
//    cancel();
  }

  public void processRosterInfo(IncomingMessage msg) throws IOException {
    isProcessInit = false;
    String header = msg.getHeader();
    if (header.equals("IRO")) {
      String destLoginName = msg.get(2);
      String destFriendlyName = msg.get(3);

      MsnFriend friend = new MsnFriend(destLoginName);
      friend.setFriendlyName(destFriendlyName);

      addMsnFriend(friend);
    }
    else
    if (header.equals("ANS")) {
      removeInfiniteTransactionId(msg.getTransactionId());
      String returnCode = msg.get(0);
      if (returnCode.equals("OK")) {
        msn.fireSwitchboardSessionStartedEvent(this);
      }
    }
  }

  /**
   * ?????? ???; ???? ?ν???? ????? ?????? '?? ????带
   * ????? ?ε??? ??;?? <b>~~</b> ????4? ????????.
   */
  protected void processTypingUser(IncomingMessage msg, MimeMessage mime) throws
      IOException {
    // ?? ????? ???? ??????? ?????????.
    MsnFriend friend = new MsnFriend(msg.get(0), msg.get(1));
    msn.fireProgressTypingEvent(this, friend, mime.getProperty("TypingUser"));
  }

  /**
   * ?ν???? ????? ???????;?? ?? ????? ó????? ???????.
   */
  protected void processInstantMessage(IncomingMessage msg, MimeMessage mime) throws
      IOException {
    MsnFriend friend = new MsnFriend(msg.get(0));
    friend.setFriendlyName(msg.get(1));
    msn.fireInstantMessageEvent(this, friend, mime);

  }

  /**
   * 发送Mime消息
   */
  public void sendMessage(MimeMessage mime) throws IOException {
    /*
     * markTransactionId?? ???? ?????? ???.
     */
    OutgoingMessage out = new OutgoingMessage("MSG");
    markTransactionId(out);
    out.add("N");
    sendMimeMessage(out, mime);
    activeTime = System.currentTimeMillis();
  }

//	/**
//	 * ?? ????? ???? ???? ????; ???????? ????? ??????.
//	 */
//	public void sendFileRequest( ToSendFile file, FileTransferMessage mime ) throws IOException
//	{
//		this.file.registerSend( file );
//		sendMessage( mime );
//	}

//	/**
//	 * ????8?κ????? ???? ??? ???; <b>???</b>???.
//	 *
//	 * @param  cookie  ???? ????? ???? ?????.
//	 * @param  toReceive  ???ε??? ?????? ????? ????.
//	 */
//	public void acceptFileReceive( int cookie, java.io.File toReceive ) throws IOException
//	{
//		this.file.registerReceive( cookie, toReceive );
//		sendMessage( FileTransferMessage.createAcceptMessage(cookie) );
//	}

  /**
   * ????8?κ????? ???? ??? ???; <b>????</b>???.
   *
   * @param  cookie  ???? ????? ???? ?????.
   */
  public void rejectFileReceive(int cookie) throws IOException {
//		sendMessage( FileTransferMessage.createRejectMessage(cookie) );
  }

  /**
   * ????? ?????? ????? ??????.
   */
  public void sendTypingMessage(MimeMessage mime) throws IOException {
    mime.setKind(MimeMessage.KIND_TYPING_USER);
    sendMessage(mime);
  }

  /**
   * ?ν???? ????? ??????.
   */
  public void sendInstantMessage(MimeMessage mime) throws IOException {
    mime.setKind(MimeMessage.KIND_MESSAGE);
    sendMessage(mime);
  }

  /**
   * ?? ????8?? ????? ??????.
   */
  public void inviteFriend(String loginName) throws IOException {
    OutgoingMessage out = new OutgoingMessage("CAL");
    markTransactionId(out);
    out.add(loginName);
    sendMessage(out);
  }

  /**
   *
   * @param processType int 回调函数类型
   * @param args Object[] 函数参数
   * @todo Implement this vitular.jmsnlib.entity.CallbackListener method
   */
  public void callbackEvent(int processType, IncomingMessage args) {
    try {
      switch (processType) {
        case PROCESS_ROSTER_INFO:
          processRosterInfo(args);
          break;
        case PROCESS_USER_CALL:
          processUserCall(args);
          break;
        case PROCESS_CALL_RESULT:
          processCallResult(args);
          break;

      }
    }
    catch (Exception e) {
    }
  }

  public void processCallResult(IncomingMessage msg) throws IOException {}

  public void processUserCall(IncomingMessage msg) throws IOException {}

  /**
   *
   * @throws IOException
   * @todo Implement this vitular.msnp.AbstractProcessor method
   */
  protected synchronized void sentPollMessage() throws IOException {
    if(System.currentTimeMillis() - activeTime > timeOut)
    {
      cleanUp();
      return;
    }
    super.sentPollMessage();
  }
}

⌨️ 快捷键说明

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