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

📄 fakeserver.java

📁 SIP(Session Initiation Protocol)是由IETF定义
💻 JAVA
字号:
/* ==================================================================== * The Vovida Software License, Version 1.0  *  * Copyright (c) 2000 Vovida Networks, Inc.  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. The names "VOCAL", "Vovida Open Communication Application Library", *    and "Vovida Open Communication Application Library (VOCAL)" must *    not be used to endorse or promote products derived from this *    software without prior written permission. For written *    permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor *    may "VOCAL" appear in their name, without prior written *    permission of Vovida Networks, Inc. *  * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY 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. *  * ==================================================================== *  * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc.  For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */package vocal.fakeServer;import java.net.ServerSocket;import java.net.Socket;import java.net.InetAddress;import java.io.PrintWriter;import java.io.OutputStreamWriter;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.FileReader;import java.io.File;import java.io.IOException;import java.io.FileNotFoundException;import java.util.Enumeration;import java.util.StringTokenizer;public class FakeServer{  private static int BLOCK_SIZE = 1024;  private String host = "localhost";  //private static int port = 6005;  private static int port = 33606;    // the text to be returned from next client interaction  protected String clientMessageString = "";  // the file to read the next client interaction from  protected File clientMessageFile = null;  // true if message should be read from clientMessageString  // false if message should be read from clientMessageFile  protected boolean readFromClientMessageString = true;  // a common object to synchronize on  protected Object lock = new Object();  // socket used for connecting to client  private ServerSocket serverSocket;    public FakeServer()  {    try    {       System.out.println("listening on port " + Integer.toString(port));       serverSocket = new ServerSocket(port);       Thread stdinThread = new Thread(new ReadFromStdin());       stdinThread.start();    }    catch (Exception e)    {      e.printStackTrace();      System.exit(1);    }  }  private void start()  {    BufferedReader reader = null;    PrintWriter writer = null;    while(true)    {      try      {        System.out.println("server waiting to accept");        Socket clientSocket = serverSocket.accept();        System.out.println("server accepted");        reader = new BufferedReader(          new InputStreamReader(clientSocket.getInputStream()));        writer = new PrintWriter(clientSocket.getOutputStream(), true);      }      catch(IOException e)      {        e.printStackTrace();        System.exit(1);      }      handleClientInput(reader, writer);    }  }  /**   * Handle a CONFIG_REQ.   */   private String handleConfigReq(Enumeration e)   {     int expectedVersionNumber = 26;     int receivedNumber = 0;     int increment = 0;     synchronized(lock)     {        String versionNumber = ((String)e.nextElement()).trim();        try        {          receivedNumber = Integer.parseInt(versionNumber);        }        catch(NumberFormatException ex)        {          ex.printStackTrace();          System.exit(1);        }        if ((receivedNumber >= expectedVersionNumber)          &&(increment++ % 10 != 0))        {          return "<data/>";        }        return handleContentRequest(e);     }   }  /*   * This is synchronized because the stdinThread updates the   * text to be returned.   * @return the response to return to the sender of this CONFIG_REQ   */  private String handleContentRequest(Enumeration e)  {    synchronized(lock)    {      if (readFromClientMessageString)      {        return clientMessageString;      }      else      {        FileReader in = null;        try        {          in = new FileReader(clientMessageFile);        }        catch(FileNotFoundException noFileEx)        {          noFileEx.printStackTrace();          System.exit(1);        }        StringBuffer content = new StringBuffer();				int c;        try        {          while ((c = in.read()) != -1)          {            content.append((char)c);          }        }        catch (IOException ioEx)        {          ioEx.printStackTrace();          System.exit(1);        }        return new String(content);      }    }  }	private void writeContent(String content, PrintWriter writer)	{    writer.write("200 OK\n");    writer.write("Content-Length: " + content.length() + "\n");    writer.write(content, 0, content.length());    writer.flush();    System.out.println("wrote " + content);	}  private String handleClientInput(BufferedReader reader, PrintWriter writer)  {		LOOP:    while(true)    {       String firstLine = null;       try       {         firstLine = reader.readLine();         if (firstLine == null)         {           return null;         }         StringTokenizer s = new StringTokenizer(firstLine, ",");         if (!s.hasMoreElements())         {           continue LOOP;         }         String firstToken = (String)s.nextElement();         if (firstToken.trim().equals("CONFIG_REQ"))         {           //String retString = handleContentRequest(s);           String retString = handleConfigReq(s);					 writeContent(retString, writer);           continue LOOP;         }         else if (firstToken.equals("GET"))         {           String retString = handleContentRequest(s);					 writeContent(retString, writer);           continue LOOP;         }				 // this case attempts to handle a browser request         else if (firstToken.equals("Accept-Charset:"))         {           String retString = handleContentRequest(s);					 writer.write(retString);					 writer.flush();           continue LOOP;         }         else         {           // just send some xml over           writer.write("<ok/>");					 writer.flush();           continue LOOP;         }      }      catch(Exception e)      {        e.printStackTrace();        System.exit(1);      }    }  }  public static void main(String args[])  {    if (args.length > 0)    {      try      {        port = Integer.parseInt(args[0]);      }      catch (NumberFormatException e)      {        System.out.println("error: non-numeric argument " + args[0]);      }    }    new FakeServer().start();  }	/**	 * This Runnable class handles requests from stdin to change the type of response	 * the socket server will give.	 */  class ReadFromStdin implements Runnable  {    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));    String userInput;    public void run()    {      try      {        LOOP: while((userInput = stdin.readLine()) != null)        {          StringTokenizer s = new StringTokenizer(userInput);          if (s.hasMoreElements())          {            String firstToken = (String)s.nextElement();            if (firstToken.equals("-f"))            {              if (!s.hasMoreElements())              {                System.out.println("please give me a filename");                break LOOP;              }              synchronized(lock)              {                String name = (String)s.nextElement();                clientMessageFile = new File(name);                readFromClientMessageString = false;                System.out.println("set clientMessageFile to "                + name);              }              continue LOOP;            }            if (firstToken.equals("-s"))            {              if (!s.hasMoreElements())              {                System.out.println("please give me the string to send");                break LOOP;              }              StringBuffer sbuf = new StringBuffer();              while(s.hasMoreElements())              {                sbuf.append((String)s.nextElement() + " ");              }              synchronized(lock)              {                clientMessageString = sbuf.toString();                readFromClientMessageString = true;                System.out.println("set clientMessageString to "                + clientMessageString);              }              continue LOOP;            }            System.out.println(firstToken + " not a recognized option"            + " try -s or -f");          }        }      }      catch(Exception e)      {        e.printStackTrace();        System.exit(1);      }    }  }}

⌨️ 快捷键说明

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