Servlet Server Socket Communication problem

Hi
Iam having this problem ...when I read data in server line by line it works but when I try to read byte by byte server hangs. This is my code
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
//it works fine when i do
String strLine = in.readLine();
//but hangs when I do like this
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int r = in.read();
while(r != -1)
baos.write(r);
r = in.read();
I am sending data from the client socket as
out = new PrintWriter(addArtSocket.getOutputStream(), true);
I just do out.println to send data.
Is there something wrong that I am doing?
Thanks
vinitha

hi,
basically, I suggest that you have the communication
channel in the same type between two ends. For example,
if you decide to connect two side byt Stream, you just
apply your code in the sort of Stream for I/O.
If you decide to connect two sides by Reader/Writer, you
apply your code in the sort of Reader/Writer for I/O.
Don't mix them up. Although I don't know what may
happen. For example, you want to pass an Object
between two ends, you could use ObjectInputStream/
ObjectOutputStream pair on two sides. Don't put
ObjectInputStream in one side and talk to one sied
which write data by other OutputStream filteer but
not ObjectOutputStream .
You may find something interesting.
good luck,
Alfred Wu

Similar Messages

  • Socket communication problem

    hello all,
    i have written a small program to send a message to echo server and get back the response from the server.
    it gives a error as
    COULD NOT GET I/O FOR CONNECTION TO <ip address>
    i am working on win nt version 4 service pack 4 installed on a home computer.
    the code is as below:
    import java.io.*;
    import java.net.*;
    public class net4a {
    public static void main(String[] args) throws IOException{
    Socket echoSocket = null;
    DataOutputStream os = null;
    DataInputStream is = null;
         DataInputStream stdIn = new DataInputStream(System.in);
         InetAddress host = InetAddress.getLocalHost();
    try {
    echoSocket = new Socket(host, 7);
    os = new DataOutputStream(echoSocket.getOutputStream());
    is = new DataInputStream(echoSocket.getInputStream());
    } catch (UnknownHostException e) {
    System.err.println("Don't know about host: " + host);
    } catch (IOException e) {
    System.err.println("Couldn't get I/O for the connection to: " + host);
    if (echoSocket != null && os != null && is != null) {
    try {
    String userInput;
    while ((userInput = stdIn.readLine()) != null) {
    os.writeBytes(userInput);
    os.writeByte('\n');
    System.out.println("echo: " + is.readLine());
    os.close();
    is.close();
    echoSocket.close();
    } catch (IOException e) {
    System.err.println("I/O failed on the connection to: " + host);
    look forward to ur valuable tips on the same.

    Hello,
    Long time java programmer, first time forum user.
    Looks like you looking to looking to get a java applet/program communicating with a web server. This is not an extremely difficult task and I have successfully got apache communicating CGI transactions to and from an applet with no drama�s.
    This is very useful as it is restrictive to have to open up extra sockets across a network as many networks today restrict socket communication often for security or business/organization policies.
    An alternative is to use HTTP request using the POST command to talk to a web server with the web server replying to the request. For example, you may need to ask a database to pull out all customer names from a server-side database. The applet need only send a URLEncoded request to the server, the webserver invokes the CGI process (I use Java to handle the CGI requests but other methods/languages can be used) which returns the result of the transaction.
    I have listed some code that included the a �ping-pong� request to a server. It included the applet function that calls the webserver, the CGI batch script (for win NT/XP) to invoke the java program, the cgi-lib to simply parse the URL request (many thanks to the author) and the server-side java program that responds to the request.
    I hope you find this useful. The download for apache, the webserver, is available at
    http://www.apache.org/
    and is a pretty simple install. Make sure you fix up the httpd.conf file to suit your system.
    Good luck.
    Dale Miller
    CLIENT-SIDE (Java Applet Snippit)
    public class Comm {
         private String server;
         private URL toServer;
         private URLConnection uRLConnection;
         private DataOutputStream dataOutputStream;
         private StringBuffer output;
         private BufferedReader dataInputStream;
         private String result;
         private int resultsLast;
         private String results[] = new String[100];
         private int firstTU;
         //this function starts in its own thread and takes care
         //of logins and there re-tries, the messaging.
         //Please see the actual function for better details
         //private LoginWatcher loginWatcher;
         public Comm(String serverAddress) throws UnsupportedEncodingException{
              System.out.println("loaded Comm class!");
              //First thing we need to do is set up the login watcher
              //loginWatcher = new LoginWatcher();
              this.output = new StringBuffer();
              this.server = serverAddress;
              try {
                   this.toServer = new URL(server + "ping.cgi");
              } catch (MalformedURLException e) {
                   System.out.println("ERROR : in contacting the server");
                   System.out.println("Server : " + server);
                   System.out.println("NOT FOUND!!");
              try {
                   this.uRLConnection = toServer.openConnection();
              } catch (IOException e) {
                   System.out.println("ERROR : Connection to server refused");
              this.uRLConnection.setUseCaches(false);
              this.uRLConnection.setDoInput(true);
              this.uRLConnection.setDoOutput(true);
              this.uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
              try {
                   this.dataOutputStream = new DataOutputStream(uRLConnection.getOutputStream());
              } catch (IOException e) {
                   System.out.println("ERROR : opening dataoutputstream");
              this.output.setLength(0);
              output.append("first=" + URLEncoder.encode("I am", "UTF-8"));
              output.append("&last=" + URLEncoder.encode("number 1", "UTF-8"));
              try {
                   dataOutputStream.writeBytes(new String(output));
              } catch (IOException e) {
                   System.out.println("ERROR : Sending string to cgi ping.cgi");
              try {
                   this.dataInputStream = new BufferedReader(new InputStreamReader(uRLConnection.getInputStream()));
              } catch (IOException e) {
                   System.out.println("ERROR : Setting up input stream");
              String grab = new String();
              System.out.print("Searching for server..");
              try {
                   grab = dataInputStream.readLine();
                   grab = dataInputStream.readLine();
              } catch (IOException e) {
                   System.out.println("ERROR : Reciving ping data from server");
              if (grab.equals("pass")) {
                   System.out.println("OK");
              } else {
                   System.out.println("ERROR\n\nSERVER NOT FOUND!!!");
                   System.exit(-1);
              //loginWatcher.loginWatcherTh.start();
    CGI BATCH TO INVOKE CGI PROGRAM
    #!java -cp c:\ss\ middle
    CGI-LIB TO PARSE HTTP REQUESTS
    import java.util.*;
    import java.io.*;
    * cgi_lib.java<p>
    * <p>
    * Usage: This library of java functions, which I have encapsulated inside
    * a class called cgi_lib as class (static) member functions,
    * attempts to duplicate the standard PERL CGI library (cgi-lib.pl).
    * You must invoke any Java program that uses this library from
    * within a UNIX script, Windows batch file or equivalent. As you
    * will see in the following example, all of the CGI environment
    * variables must be passed from the script into the Java application
    * using the -D option of the Java interpreter. This example
    * UNIX script uses the "main" routine of this class as a
    * CGI script:
    * <pre>
    * (testcgi.sh)
    * #!/bin/sh
    * java \
    * -Dcgi.content_type=$CONTENT_TYPE \
    * -Dcgi.content_length=$CONTENT_LENGTH \
    * -Dcgi.request_method=$REQUEST_METHOD \
    * -Dcgi.query_string=$QUERY_STRING \
    * -Dcgi.server_name=$SERVER_NAME \
    * -Dcgi.server_port=$SERVER_PORT \
    * -Dcgi.script_name=$SCRIPT_NAME \
    * -Dcgi.path_info=$PATH_INFO \
    * cgi_lib
    * </pre>
    * Question and comments can be sent to [email protected].<p>
    * @version 1.0
    * @author Pat L. Durante
    class cgi_lib
    * Parse the form data passed from the browser into
    * a Hashtable. The names of the input fields on the HTML form will
    * be used as the keys to the Hashtable returned. If you have a form
    * that contains an input field such as this,<p>
    * <pre>
    * &ltINPUT SIZE=40 TYPE="text" NAME="email" VALUE="[email protected]"&gt
    * </pre>
    * then after calling this method like this,<p>
    * <pre>
    * Hashtable form_data = cgi_lib.ReadParse(System.in);
    * </pre>
    * you can access that email field as follows:<p>
    * <pre>
    * String email_addr = (String)form_data.get("email");
    * </pre>
    * @param inStream The input stream from which the form data can be read.
    * (Only used if the form data was posted using the POST method. Usually,
    * you will want to simply pass in System.in for this parameter.)
    * @return The form data is parsed and returned in a Hashtable
    * in which the keys represent the names of the input fields.
    public static Hashtable ReadParse(InputStream inStream)
    Hashtable form_data = new Hashtable();
    String inBuffer = "";
    if (MethGet())
    inBuffer = System.getProperty("cgi.query_string");
    else
    // TODO: I should probably use the cgi.content_length property when
    // reading the input stream and read only that number of
    // bytes. The code below does not use the content length
    // passed in through the CGI API.
    DataInput d = new DataInputStream(inStream);
    String line;
    try
    while((line = d.readLine()) != null)
    inBuffer = inBuffer + line;
    catch (IOException ignored) { }
    // Split the name value pairs at the ampersand (&)
    StringTokenizer pair_tokenizer = new StringTokenizer(inBuffer,"&");
    while (pair_tokenizer.hasMoreTokens())
    String pair = urlDecode(pair_tokenizer.nextToken());
    // Split into key and value
    StringTokenizer keyval_tokenizer = new StringTokenizer(pair,"=");
    String key = new String();
    String value = new String();
    if (keyval_tokenizer.hasMoreTokens())
    key = keyval_tokenizer.nextToken();
    else ; // ERROR - shouldn't ever occur
    if (keyval_tokenizer.hasMoreTokens())
    value = keyval_tokenizer.nextToken();
    else ; // ERROR - shouldn't ever occur
    // Add key and associated value into the form_data Hashtable
    form_data.put(key,value);
    return form_data;
    * URL decode a string.<p>
    * Data passed through the CGI API is URL encoded by the browser.
    * All spaces are turned into plus characters (+) and all "special"
    * characters are hex escaped into a %dd format (where dd is the hex
    * ASCII value that represents the original character). You probably
    * won't ever need to call this routine directly; it is used by the
    * ReadParse method to decode the form data.
    * @param in The string you wish to decode.
    * @return The decoded string.
    public static String urlDecode(String in)
    StringBuffer out = new StringBuffer(in.length());
    int i = 0;
    int j = 0;
    while (i < in.length())
    char ch = in.charAt(i);
    i++;
    if (ch == '+') ch = ' ';
    else if (ch == '%')
    ch = (char)Integer.parseInt(in.substring(i,i+2), 16);
    i+=2;
    out.append(ch);
    j++;
    return new String(out);
    * Generate a standard HTTP HTML header.
    * @return A String containing the standard HTTP HTML header.
    public static String Header()
    return "Content-type: text/html\n\n";
    * Generate some vanilla HTML that you usually
    * want to include at the top of any HTML page you generate.
    * @param Title The title you want to put on the page.
    * @return A String containing the top portion of an HTML file.
    public static String HtmlTop(String Title)
    String Top = new String();
    Top = "<html>\n";
    Top+= "<head>\n";
    Top+= "<title>\n";
    Top+= Title;
    Top+= "\n";
    Top+= "</title>\n";
    Top+= "</head>\n";
    Top+= "<body>\n";
    return Top;
    * Generate some vanilla HTML that you usually
    * want to include at the bottom of any HTML page you generate.
    * @return A String containing the bottom portion of an HTML file.
    public static String HtmlBot()
    return "</body>\n</html>\n";
    * Determine if the REQUEST_METHOD used to
    * send the data from the browser was the GET method.
    * @return true, if the REQUEST_METHOD was GET. false, otherwise.
    public static boolean MethGet()
    String RequestMethod = System.getProperty("cgi.request_method");
    boolean returnVal = false;
    if (RequestMethod != null)
    if (RequestMethod.equals("GET") ||
    RequestMethod.equals("get"))
    returnVal=true;
    return returnVal;
    * Determine if the REQUEST_METHOD used to
    * send the data from the browser was the POST method.
    * @return true, if the REQUEST_METHOD was POST. false, otherwise.
    public static boolean MethPost()
    String RequestMethod = System.getProperty("cgi.request_method");
    boolean returnVal = false;
    if (RequestMethod != null)
    if (RequestMethod.equals("POST") ||
    RequestMethod.equals("post"))
    returnVal=true;
    return returnVal;
    * Determine the Base URL of this script.
    * (Does not include the QUERY_STRING (if any) or PATH_INFO (if any).
    * @return The Base URL of this script as a String.
    public static String MyBaseURL()
    String returnString = new String();
    returnString = "http://" +
    System.getProperty("cgi.server_name");
    if (!(System.getProperty("cgi.server_port").equals("80")))
    returnString += ":" + System.getProperty("cgi.server_port");
    returnString += System.getProperty("cgi.script_name");
    return returnString;
    * Determine the Full URL of this script.
    * (Includes the QUERY_STRING (if any) or PATH_INFO (if any).
    * @return The Full URL of this script as a String.
    public static String MyFullURL()
    String returnString;
    returnString = MyBaseURL();
    returnString += System.getProperty("cgi.path_info");
    String queryString = System.getProperty("cgi.query_string");
    if (queryString.length() > 0)
    returnString += "?" + queryString;
    return returnString;
    * Neatly format all of the CGI environment variables
    * and the associated values using HTML.
    * @return A String containing an HTML representation of the CGI environment
    * variables and the associated values.
    public static String Environment()
    String returnString;
    returnString = "<dl compact>\n";
    returnString += "<dt><b>CONTENT_TYPE</b> <dd>:<i>" +
    System.getProperty("cgi.content_type") +
    "</i>:<br>\n";
    returnString += "<dt><b>CONTENT_LENGTH</b> <dd>:<i>" +
    System.getProperty("cgi.content_length") +
    "</i>:<br>\n";
    returnString += "<dt><b>REQUEST_METHOD</b> <dd>:<i>" +
    System.getProperty("cgi.request_method") +
    "</i>:<br>\n";
    returnString += "<dt><b>QUERY_STRING</b> <dd>:<i>" +
    System.getProperty("cgi.query_string") +
    "</i>:<br>\n";
    returnString += "<dt><b>SERVER_NAME</b> <dd>:<i>" +
    System.getProperty("cgi.server_name") +
    "</i>:<br>\n";
    returnString += "<dt><b>SERVER_PORT</b> <dd>:<i>" +
    System.getProperty("cgi.server_port") +
    "</i>:<br>\n";
    returnString += "<dt><b>SCRIPT_NAME</b> <dd>:<i>" +
    System.getProperty("cgi.script_name") +
    "</i>:<br>\n";
    returnString += "<dt><b>PATH_INFO</b> <dd>:<i>" +
    System.getProperty("cgi.path_info") +
    "</i>:<br>\n";
    returnString += "</dl>\n";
    return returnString;
    * Neatly format all of the form data using HTML.
    * @param form_data The Hashtable containing the form data which was
    * parsed using the ReadParse method.
    * @return A String containing an HTML representation of all of the
    * form variables and the associated values.
    public static String Variables(Hashtable form_data)
    String returnString;
    returnString = "<dl compact>\n";
    for (Enumeration e = form_data.keys() ; e.hasMoreElements() ;)
    String key = (String)e.nextElement();
    String value = (String)form_data.get(key);
    returnString += "<dt><b>" + key + "</b> <dd>:<i>" +
    value +
    "</i>:<br>\n";
    returnString += "</dl>\n";
    return returnString;
    * The main routine is included here as a test CGI script to
    * demonstrate the use of all of the methods provided above.
    * You can use it to test your ability to execute a CGI script written
    * in Java. See the sample UNIX script file included above to see
    * how you would invoke this routine.<p>
    * Please note that this routine references the member functions directly
    * (since they are in the same class), but you would have to
    * reference the member functions using the class name prefix to
    * use them in your own CGI application:<p>
    * <pre>
    * System.out.println(cgi_lib.HtmlTop());
    * </pre>
    * @param args An array of Strings containing any command line
    * parameters supplied when this program in invoked. Any
    * command line parameters supplied are ignored by this routine.
    public static void main( String args[] )
    // This main program is simply used to test the functions in the
    // cgi_lib class.
    // That said, you can use this main program as a test cgi script. All
    // it does is echo back the form inputs and enviroment information to
    // the browser. Use the testcgi UNIX script file to invoke it. You'll
    // notice that the script you use to invoke any Java application that
    // uses the cgi_lib functions MUST pass all the CGI enviroment variables
    // into it using the -D parameter. See testcgi for more details.
    // Print the required CGI header.
    System.out.println(Header());
    // Create the Top of the returned HTML
    // page (the parameter becomes the title).
    System.out.println(HtmlTop("Hello World"));
    System.out.println("<hr>");
    // Determine the request method used by the browser.
    if (MethGet())
    System.out.println("REQUEST_METHOD=GET");
    if (MethPost())
    System.out.println("REQUEST_METHOD=POST");
    System.out.println("<hr>");
    // Determine the Base URL of this script.
    System.out.println("Base URL: " + MyBaseURL());
    System.out.println("<hr>");
    // Determine the Full URL used to invoke this script.
    System.out.println("Full URL: " + MyFullURL());
    System.out.println("<hr>");
    // Print all the CGI environment variables
    // (usually only used while testing CGI scripts).
    System.out.println(Environment());
    System.out.println("<hr>");
    // Parse the form data into a Hashtable.
    Hashtable form_data = ReadParse(System.in);
    // Print out each of the name/value pairs
    // from sent from the browser.
    System.out.println(Variables(form_data));
    System.out.println("<hr>");
    // Access a particular form value.
    // (This assumes the form contains a "name" input field.)
    String name = (String)form_data.get("name");
    System.out.println("Name=" + name);
    System.out.println("<hr>");
    // Create the Bottom of the returned HTML page - which closes it cleanly.
    System.out.println(HtmlBot());
    SERVER-SIDE PROGRAM TO RETURN PING
    import java.util.*;
    import java.io.*;
    class ping
         public static void main(String args[]) {
              System.out.println(cgi_lib.Header());
              Hashtable form_data = cgi_lib.ReadParse(System.in);
              String one = (String)form_data.get("first");
              String two = (String)form_data.get("last");
              boolean test;
              test = false;
              if (one.equals("I am")) {
                   if (two.equals("number 1")) {
                        test = true;
              if (test == true) {
                   System.out.println("pass");
              } else {
                   System.out.println("fail");
         //Datavasee
    ENJOY :)

  • BI Server Socket communication error

    All,
    OBIEE 10G with Oracle 11 database on Sun solaris.
    BI Server is randomly crashing with following error message:
    Odbc driver returned an error (SQLDriverConnectW).
    State: HY000. Code: 0. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 12008]
    Unable to connect to port 9703 on machine LOCALHOST. [nQSError: 12010]
    Communication error connecting to remote end point: address = LOCALHOST; port = 9703. [nQSError: 12002]
    Socket communication error at call=: (Number=-1) Unknown error (HY000)
    If you restart, it works fine for 1-2 days. Then again crash happens.
    Any ideas ..?
    ~R

    I've had similar issues due to insufficient memory on HP-UX. Probably best to raise a support log with oracle.

  • Servlet Applet object communication problem???!!!

    Hy folks,
    I need to validate the ability of complex Servlet Applet communication an run into my first pb right at the beginning of my tests. I need to have around 200 Applet clients connect to my servlet and communicate by ObjectInput and ObjectOutput streams. So I wrote a simple Servlet accepting HTTP POST connections that return a Java object. When the java Applet get instantiated, the Object Stream communication workes fine. But when the Applet tries to communicate with the servlet after that, I can not create another communication session with that Servlet, instead I get a 405 Method not allowed exception.
    Summarized:
    - Applet init() instantiate URLConnection with Servlet and request Java object (opening ObjectInput and Output Stream, after receaving object, cloasing streams).
    - When I press a "get More" button on my Applet, I am not able to instantiate a new URLConnection with my servler because of that 405 exception, WHY???
    Here my Servlet code:
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
             ObjectInputStream inputFromApplet = null;
             ArrayList transmitContent = null;       
             PrintWriter out = null;
             BufferedReader inTest = null;
             try{               
                   inputFromApplet = new ObjectInputStream(request.getInputStream());           
                     transmitContent = (ArrayList) inputFromApplet.readObject();       
                     inputFromApplet.close();
                     ArrayList toReturn = new ArrayList();                 
                     toReturn.add("One");
                     toReturn.add("Two");
                     toReturn.add("Three");
                     sendAnsweredList(response, toReturn);                 
             catch(Exception e){}        
         public void sendAnsweredList(HttpServletResponse response, ArrayList returnObject){
             ObjectOutputStream outputToApplet;    
              try{
                  outputToApplet = new ObjectOutputStream(response.getOutputStream());          
                  outputToApplet.writeObject(returnObject);
                  outputToApplet.flush();           
                  outputToApplet.close();              
              catch (IOException e){
                     e.printStackTrace();
    }Here my Applet code:
    public void init() {         
             moreStuff.addActionListener(new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                       requestMore();
             try{
                  studentDBservlet = new URL("http://localhost/DBHandlerServlet");              
                  servletConnection = studentDBservlet.openConnection();      
                   servletConnection.setUseCaches (false);
                   servletConnection.setDefaultUseCaches(false);
                   servletConnection.setDoOutput(true);
                   servletConnection.setDoInput(true);
                   ObjectOutputStream outputToApplet;
                 outputToApplet = new ObjectOutputStream(servletConnection.getOutputStream());          
                 outputToApplet.writeObject(new ArrayList());
                 outputToApplet.flush();           
                 outputToApplet.close(); 
                   ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                   ArrayList studentVector = (ArrayList) inputFromServlet.readObject();
                   area.setText("Success!\n");
                   for (int i = 0; i<studentVector.size(); i++) {
                        area.append(studentVector.get(i).toString()+"\n");
                  inputFromServlet.close();
                  outputToApplet.close();             
              catch(Exception e){
                   area = new JTextArea();
                   area.setText("An error occured!!!\n");
                   area.append(e.getMessage());
            getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
            getContentPane().add(moreStuff, BorderLayout.SOUTH);
        private void requestMore(){
             try{              
                  studentDBservlet = new URL("http://localhost/DBHandlerServlet");                             
                  servletConnection = studentDBservlet.openConnection(); 
                   ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                   ArrayList studentVector = (ArrayList) inputFromServlet.readObject();
                   area.setText("Success2!\n");
                   for (int i = 0; i<studentVector.size(); i++) {
                        area.append(studentVector.get(i).toString()+"\n");
              catch(Exception e){               
                   area.setText("An error occured2!!!\n");
                   area.append(e.getMessage());
        }Can someone help me solv this issue please, this is my first Applet Servlet work so far so I have no idea on how to solve this issue.

    Sorry folks, just found my error. Forgot about the ObjectInputStream waiting on the Servlet side, so of course had a dead look...
    Sorry!

  • Client / Server Socket Communication - Should use 2 ports?

    If we have a client server architecture using a socket based connection, should there be 2 serperate sockets? One dedicated to sending and one dedictated to receiving? What happens if both the client and server both send at the same time? How does that get handled? Does one of the messages get dropped? Thanks...

    There are of course reasons you might want to use two sockets.
    For instance security. One socket is encrypted and the other isn't. Or because the server initiates a confirmed port connection back it verifies the IP.
    Or because the main socket is used for control and the second one is used for data. That way the client can tell the server to pause or make other adjustments in the data while the data is still flowing.

  • Problem with socket communications

    I am trying to put together a client server socket communication pair.
    I have one application that runs in the background acting as a server and another that can be started and stopped that acts as a client.
    I can start the server and create a server socket with no problem.
    I can start the client and it connects to the server.
    The server acknowledges the connection and appears to go into a blocking state waiting for the client to send another message.
    The server blocks at the line
    parent.logit("Waiting for message from EVR..... ");
    The problem is that when the client sends another message, the server doesn't hear it.
    I am not sure if the problem is with the client or server communication code.
    If anyone out there is a socket communication guru, I would appreciate it if you could tell me what I am doing wrong.
    Thanks
    Server code:
    import java.io.*;
    import java.net.*;
    public class EVRServer
        extends Thread
      EVRDataLoader parent = null;
      ServerSocket serverSock = null;
      Socket clientSock = null;
      BufferedReader reader = null;
      BufferedWriter writer = null;
      int evrPort = 0;
      int retryLimit = 10;
      int retryCount = 0;
      boolean alive = false;
      boolean killSocket = false;
      boolean evrConnected = false;
      boolean retry = true;
      EVRListener evrListener = null;
    //=============================================================================
    // Full constructor
    //=============================================================================
       * Full constructor.
       * @param dl DataLoader - Parent application
       * @param port int Socket port
      public EVRServer(EVRDataLoader dl, int port)
        parent = dl;
        evrPort = port;
    //=============================================================================
    //  Run method - Main thread executed by start() method
    //=============================================================================
       * Main thread executed by start() method
      public void run()
        while (retry)
          if (retryCount > retryLimit)
            retry = false;
          parent.logit("Retry count = " + retryCount);
          // Create new server socket connection
          if (serverSock == null)
            try
              serverSock = new ServerSocket(evrPort);
              parent.logit("Created Server Socket for EVR on port " + evrPort);
              alive = true;
              killSocket = false;
              evrConnected = false;
            catch (Exception e)
              parent.logit(
                  "ERROR - Could not create Server socket connection for EVR: " +
                  e.toString());
              killSocket = true;
              alive = false;
          // Create new client socket connection
          if (clientSock == null)
            try
              parent.logit("Waiting for EVR to connect");
              clientSock = null;
              clientSock = serverSock.accept();
              retryCount = 0;
              evrConnected = true;
              killSocket = false;
              parent.logit("EVR connected on server Socket Port " + evrPort);
            catch (Exception e)
              parent.logit("ERROR - Error accepting EVR connection: " + e.toString());
              killSocket = true;
            try
              reader = new BufferedReader(new InputStreamReader(
                  clientSock.getInputStream()));
              writer = new BufferedWriter(new OutputStreamWriter(
                  clientSock.getOutputStream()));
              parent.logit( "Created reader "+reader);
              parent.logit( "Created writer "+writer);
            catch (Exception e)
              parent.logit(
                  "ERROR - creating reader or writer to EVR: " + e.toString());
              killSocket = true;
          int nullCount = 0;
          while (killSocket == false)
            try
              parent.logit("Waiting for message from EVR..... ");
    //          sendMessage("Data Controller connected on port " + evrPort);
              String s = reader.readLine();
              parent.logit("EVR - Received message: " + s);
              if (s != null)
                parent.processEvrMessage( s);
              else
                sleep(1000);
                nullCount++;
                if (nullCount > 10)
                  parent.logit("Exceeded retry limit: ");
                  killSocket = true;
            catch (Exception ex)
              parent.logit("Error Reading from EVR: " + ex.toString());
              killSocket = true;
          parent.logit( "After while loop");
          evrConnected = false;
          try
            retryCount++;
            parent.logit("Closing EVR connection. ");
            reader.close();
            writer.close();
            clientSock.close();
            writer = null;
            reader = null;
            clientSock = null;
            try
              sleep(1000);
            catch (Exception ee)
              parent.logit("Error after sleep " + ee.toString());
          catch (Exception e)
            parent.logit("Error closing EVR server socket");
    //=============================================================================
    // Call this method to kill the client socket connection.
    //=============================================================================
       * Call this method to kill the client socket connection.
      public void killConnection()
        killSocket = true;
    //=============================================================================
    // Return RTM connected state
    //=============================================================================
       * Return RTM connected state
       * @return boolean - Returns true if RTM is connected to server, false if not.
      public boolean isRtmConnected()
        return evrConnected;
    //=============================================================================
    // Returns state of server socket.
    //=============================================================================
       * Returns state of server socket.
       * @return boolean - Returns true if server socket is enabled, false if not.
      public boolean isServerSocketAlive()
        return alive;
    //=============================================================================
    // Send a message to the client socket.
    //=============================================================================
         * Send a message to the client socket.
         * @param msg String - Message to send.
         * @return boolean - Returns true if message sent OK, false if not.
      public boolean sendMessage(String msg)
        parent.logit(" In EVR Server - Send Message - got message: " + msg);
        if (evrConnected)
          try
            parent.logit("Sending message to EVR: " + msg);
            writer.write(msg + "\n");
            writer.flush();
            return true;
          catch (Exception e)
            parent.logit("ERROR - Error sending message to EVR: " + e.toString());
            return false;
        else
          parent.logit("EVR not connected, cannot send message: " + msg);
          return false;
    }Client code:
    package evrsimulator;
    import java.net.*;
    import java.io.*;
    class PortConnector
          extends Thread
       ServerSocket serverSock = null;
       boolean isIP = false;
       InetAddress addr = null;
       Frame1 parent = null;
       byte[] rawIP;
        //   String initialMsg = "";
       public PortConnector( Frame1 f )
         parent = f;
       // This method is called when the thread runs
       public void run()
          if ( parent.hostName.indexOf( "." ) > 0 )
             isIP = true;
             byte[] rawIP = parent.getRawIP( parent.hostName );
          try
             System.out.println( "Connecting to host " +
                                            parent.hostName + " on port " +
                                            parent.socketPort );
             if ( isIP )
                addr = InetAddress.getByAddress( rawIP );
             else
                addr = InetAddress.getByName( parent.hostName );
             System.out.println( "Inet address = " + addr );
             SocketAddress sockaddr =
                   new InetSocketAddress( addr, parent.socketPort );
             // Create an unbound socket
             parent.client = new Socket();
             // This method will block no more than timeoutMs.
             // If the timeout occurs, SocketTimeoutException is thrown.
             parent.client.connect( sockaddr, parent.socketTimeOut );
             parent.socketOut =
                   new BufferedWriter( new OutputStreamWriter(
                   parent.client.getOutputStream() ) );
             parent.socketIn = new BufferedReader( new InputStreamReader(
                   parent.client.getInputStream() ) );
             parent.localName = parent.localName +
                   parent.client;
             System.out.println( "Parent socketOut = "+parent.socketOut);
             System.out.println( "Parent socketIn = "+parent.socketIn);
          catch ( UnknownHostException uhe )
             System.out.println( "Unknown Host - " + uhe.getMessage() );
          catch ( SocketTimeoutException ste )
             System.out.println( "Socket time out - " + ste.getMessage());
          catch ( IOException ioe )
             System.out.println( "IO exception - " + ioe.getMessage() );
          // Listen on socket for message from host - thread should block.
          parent.portConnected = true;
          while ( parent.portConnected )
             try
                String msg = parent.socketIn.readLine();
                System.out.println( "Message from Host: " + msg );
                System.out.println( "Message from Host: |" + msg + "|" );
                if( msg.length() > 2)parent.processMessage( msg );
             catch ( IOException ioe )
                System.out.println( "Exception creating server socket." );
          try
             System.out.println(
                   "PortConnection - Closing socket and IO connections" );
             parent.socketIn.close();
             parent.socketOut.close();
             parent.client.close();
             parent.clockRunning = false;
             if( parent.heartBeating) heartBeat.interrupt();
          catch ( IOException ioex )
             System.out.println( "Exception closing socket." );
    }

    Your first problem is that you keep closing and recreating the ServerSocket. Do this once only in the lifetime of the server.
    This is such a basic error that I haven't read the rest of the code. Before you go any further I suggest you read the Custom Networking trail of the Java Tutorial.

  • License server communication problem: E_ADEPT_INTERNAL ??

    When our customer downloads an epub link created by the adobe content server:
    http://acs.riverwatcher.com:8080/fulfillment/URLLink.acsm?action=enterorder&ordersource=Sa gamore+Publishing+Store&orderid=1069267236_0&resid=urn%3Auuid%3A183e17c3-e5e3-43d9-8fde-ac c0177050b2&gbauthdate=09%2F27%2F2010+18%3A54+UTC&dateval=1285613645&gblver=4&auth=94ae7877 0104329ba549893bdff875f8e4582d1a
    This allows them to open or save the following URLink.ascm file:
    <fulfillmentToken fulfillmentType="buy" xmlns="http://ns.adobe.com/adept">
      <distributor>urn:uuid:c58286f7-2655-4df5-8b63-912344f3ffe3</distributor>
      <operatorURL>http://acs.riverwatcher.com:8080/fulfillment</operatorURL>
      <expiration>2010-09-07T11:37:34-04:00</expiration>
      <transaction>123456789</transaction>
      <resourceItemInfo>
        <resource>urn:uuid:7763a743-4a7d-4153-b0c4-5bccaec539a2</resource>
        <resourceItem>1</resourceItem>
        <metadata>
          <dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">
      Edgar Poe, sa vie et ses oeuvres
    </dc:title>
          <dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">
      Baudelaire, Charles
    </dc:creator>
          <dc:format xmlns:dc="http://purl.org/dc/elements/1.1/">application/epub+zip</dc:format>
          <dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">
      Feedbooks (www.feedbooks.com)
    </dc:publisher>
    <dc:language xmlns:dc="http://purl.org/dc/elements/1.1/">
      fr
    </dc:language>
          <dc:description xmlns:dc="http://purl.org/dc/elements/1.1/"></dc:description>
          <dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/">
      urn:uuid:5f652f06-2d90-11dd-804a-001cc049a027
    </dc:identifier>
        </metadata>
        <src>http://acs.riverwatcher.com:8080/media/7763a743-4a7d-4153-b0c4-5bccaec539a2.epub</src>
        <downloadType>simple</downloadType>
      </resourceItemInfo>
      <hmac>c/D6CH3gm/2EAw54j0AwM7FDG74=</hmac>
    </fulfillmentToken>
    They receive the following error in Adobe Digital Editions:
    Error getting license
    License server communication problem: E_ADEPT_INTERNAL
    Here is the log from our acs server:
    java.lang.NullPointerException
        at java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:106)
        at com.adobe.adept.shared.request.LicenseToken.<init>(LicenseToken.java:100)
       at com.adobe.adept.fulfillment.servlet.Fulfill.writeLicense(Fulfill.java:979)
        at com.adobe.adept.fulfillment.servlet.Fulfill.doPost(Fulfill.java:1137)
        at com.adobe.adept.fulfillment.servlet.Fulfill.doPost(Fulfill.java:73)
        at com.adobe.adept.servlet.AdeptServlet.doPost(AdeptServlet.java:184)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.j ava:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.ja va:588)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Thread.java:636)
    Please advise, any help you can provide would be very helpful.  This is only happening with a select few of the books I packaged into the acs server.  Using the exact same packaging and fulfillment process works fine for many of the pdfs we uploaded.  There does not seem to be any common thread among the ones that fail vs. the ones that do not fail.
    Things we have tried:
    * Renaming the file  prior to upload to have no spaces/special characters.
    * deleting the product and trying again from scratch.
    Has ANYONE seen this before?  Or have any idea what could be the cause?
    Thank you in advance,
    Joe

    Is the transaction in the fulfillmentToken really '123456789' and not '1079267236_0'?
    At a quick look the exception is that it is unable to create a license for this.  From memory the usual error for this is that the transaction is already recorded in the fulfillment table but there is no corresponding item in the license in the license table (join the user from the fulfillment table with the resource with the fulfillment item table - join is the fulfillmentid)
    -jim

  • Communication problem with proxy server

    We have establish the configuration of an iPad to access the enterprise net, but when trying to access any webpage we get the next message: Safari can not open the page. Error:"There is a communication problem with proxy web server (HTTP)"
    The access has no problems with other movile devices.
    Ahy help?

    Hi,
    I am not sure whether you have already solved the problem or not....
    Do the following to deploy MobileBIService.war file on tomcat
    1.Stop Tomcat Web application server.
    2.Copy the file, MobileBIService.war from [Install directory]\Mobile 14\Client to the Tomcat's "Webapps" directory.
    In my case, I copied the MobileBIService.war from C:\Program Files (x86)\SAP BusinessObjects\Mobile14\Client to C:\Program Files (x86)\SAP BusinessObjects\Tomcat6\webapps. ( I used BO 4.0 SP02)
    3.     Start Tomcat.
    Restarting Tomcat would automatically deploy war file as a Web App
    One folder u201CMobileBiServiceu201D will appear in webapps folder when MobileBIService.war is deployed successfully.
    Hope it helps.
    Regards,
    Ankur

  • Communication problem the web server extension (WGATE) failed to receive a

    Hi,
    When a user tries to access his timesheet he get the below error:
    <b>communication problem the web server extension (WGATE) failed to receive a response from the ITS web service</b>
    Only ONE user is getting this error. If everyone get\s the same we can check on the ITS side, but if only ONE user is getting it.
    Please help.
    Regards,
    PK

    HI ALL,
    Thanks for your time. The issue got resolved however without cheking the logs itself. The problem was with the scripfile. All other users and all other scripts were working, except one. And it got recified.
    Regards,
    P. Kumaravel.

  • Why am I getting the error: error getting license License Server communication problem W_ADEPT_CORE_EXPIRED when I try to download a book from the public library using Adobe Digital Editions. It has been working for a few months, but now I suddenly get th

    I have checked and the Adobe Digital Editions is authorized. The library book doesn't expire for another 14 days.  These have been the only two suggestions that I have found in other forums.  Does anyone have any other suggestions?

    I am having this exact issue. I just downloaded a book and went to open it and got this exact problem.
    I purchased he book through indigo/kobo edition and paid for it and immediately went to open it and am getting the same error
    Error getting License. License Server Communication Problem only mine says  Bad Device key after.
    Not sure why someone has not answered this question yet...i am using windows 7 and this is how i always do it. Never had this problem before when purchasing a book.
    i hope someone answers this soon.

  • When I open a book in Adobe Digital Editions, I get the following error: Error getting License. License Server Communication Problem: E_ADEPT_DOCUMENT_TYPE_UNKNOWN:

    Hi, I bought an e-book in PDF format that uses Adobe DRM.  I've created an account on adobe.com and tried downloading the book in Adobe Digital Editions on the Mac (as well as the bookstore's e-reader--logged into my Adobe account--on an Android device). 
    It tries to download the book but get's the following error:
    Error getting License. License Server Communication Problem:
    E_ADEPT_DOCUMENT_TYPE_UNKNOWN:
    Has anyone come across this?  Any guidance would be most appreciated!
    Thanks!
    Tony

    Please refer to the KB article, Public Knowledge Base

  • Problem in socket communication please help me!

    server
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketServer extends JFrame
              implements ActionListener {
         JLabel text1, text2;
         JButton button1, button2;
         JPanel panel;
         JTextField textField1, textField2;
    ServerSocket server = null;
    Socket socket = null;
    BufferedReader in1 = null;
    PrintWriter out1 = null;
    String line1;
    String line2;
    SocketServer(){ //Begin Constructor
              text1 = new JLabel("Send Information:");
              text2 = new JLabel("Receive Information:");
              textField1 = new JTextField(20);
              textField2 = new JTextField(20);
              button1 = new JButton("Send");
              button2 = new JButton("Receive");
              button1.addActionListener(this);
              button2.addActionListener(this);
              panel = new JPanel();
              panel.setLayout(new GridLayout(2,3));
              panel.setBackground(Color.lightGray);
              getContentPane().add(panel);
              panel.add(text1);
              panel.add(textField1);
              panel.add(button1);
              panel.add(text2);
              panel.add(textField2);
              panel.add(button2);
              setSize(500,100);
    } //End Constructor
         public void actionPerformed(ActionEvent event) {
              Object source = event.getSource();
              if(source == button1){
                   //Send data over socket
                   String text = textField1.getText();
                   out1.println(text);
                   textField1.setText(new String(""));
                   //Receive text from server
                   try{
                        String line1 = in1.readLine();
                        System.out.println("Text received :" + line1);
                   } catch (IOException e){
                        System.out.println("Read failed");
                        System.exit(1);
              if(source == button2){
                   textField2.setText(line2);
         public void listenSocket(){
              try{
                   server = new ServerSocket(4444);
              } catch (IOException e) {
                   System.out.println("Could not listen on port 4444");
                   System.exit(-1);
              try{
                   socket = server.accept();
              } catch (IOException e) {
                   System.out.println("Accept failed: 4444");
                   System.exit(-1);
              try{
                   in1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   out1 = new PrintWriter(socket.getOutputStream(), true);
              } catch (IOException e) {
                   System.out.println("Accept failed: 4444");
                   System.exit(-1);
              while(true){
                   try{
                        line2 = in1.readLine();
                        //Send data back to client
                        out1.println(line2);
                   } catch (IOException e) {
                        System.out.println("Read failed");
                        System.exit(-1);
         protected void finalize(){
              //Clean up
              try{
                   in1.close();
                   out1.close();
                   server.close();
              } catch (IOException e) {
                   System.out.println("Could not close.");
                   System.exit(-1);
         public static void main(String[] args){
              SocketServer frame = new SocketServer();
              frame.setTitle("Chat (Server)");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.addWindowListener(l);
              frame.pack();
              frame.setVisible(true);
              frame.listenSocket();
    client
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketClient extends JFrame
              implements ActionListener {
    JLabel text1, text2;
    JButton button1, button2;
    JPanel panel;
    JTextField textField1, textField2;
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    String line3;
    String line4;
    SocketClient(){ //Begin Constructor
    text1 = new JLabel("Send Information:");
         text2 = new JLabel("Receive Information:");
    textField1 = new JTextField(20);
         textField2 = new JTextField(20);
    button1 = new JButton("Send");
         button2 = new JButton("Receive");
    button1.addActionListener(this);
         button2.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new GridLayout(2,3));
    panel.setBackground(Color.lightGray);
    getContentPane().add(panel);
    panel.add(text1);
    panel.add(textField1);
    panel.add(button1);
         panel.add(text2);
         panel.add(textField2);
         panel.add(button2);
         setSize(500,100);
    } //End Constructor
         public void actionPerformed(ActionEvent event){
              Object source = event.getSource();
              if(source == button1){
                   //Send data over socket
                   String text = textField1.getText();
                   out.println(text);
                   textField1.setText(new String(""));
                   //Receive text from server
                   try{
                        String line3 = in.readLine();
                        System.out.println("Text received :" + line3);
                   } catch (IOException e){
                        System.out.println("Read failed");
                        System.exit(1);
              if(source == button2){
                   textField2.setText(line4);
         public void listenSocket(){
              //Create socket connection
              try{
                   socket = new Socket("Localhost", 4444);
                   out = new PrintWriter(socket.getOutputStream(), true);
                   in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              } catch (UnknownHostException e) {
                   System.out.println("Unknown host: Localhost");
                   System.exit(1);
              } catch (IOException e) {
                   System.out.println("No I/O");
                   System.exit(1);
              while(true){
                   try{
                        line4 = in.readLine();
                        //Send data back to client
                        out.println(line4);
                   } catch (IOException e) {
                        System.out.println("Read failed");
                        System.exit(-1);
         public static void main(String[] args){
              SocketClient frame = new SocketClient();
              frame.setTitle("Chat (Client)");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.addWindowListener(l);
              frame.pack();
              frame.setVisible(true);
              frame.listenSocket();
    There were problems when executing the application
    please help me

    i had no problem running this... make sure you open the server part first and have that sitting and waiting for the client to connect.... then it should work.
    Would you believe that i too am working on the server / socket thing... however my problem is getting the server to read from a database and report back to the client....

  • I keep getting the following message after I download a book and try to open the book from my downloads (in finder) Error getting License. License Server Communication Problem: E_ACT_NOT_READY. It gives me no other information and no options other than to

    I don't really know what to do. I download a book from my library and it then goes to my download folder in finder (I have a macbook pro). When I double click on the downloaded book to open, digital editions comes up and then I get the following message
    Error getting License. License Server Communication Problem:
    E_ACT_NOT_READY
    The only option I have at that point is to close the window. My computer is registered/authorized and I have tried everything I can think of but can't get the books to download into adobe digital editions.
    Help please

    I am having this exact issue. I just downloaded a book and went to open it and got this exact problem.
    I purchased he book through indigo/kobo edition and paid for it and immediately went to open it and am getting the same error
    Error getting License. License Server Communication Problem only mine says  Bad Device key after.
    Not sure why someone has not answered this question yet...i am using windows 7 and this is how i always do it. Never had this problem before when purchasing a book.
    i hope someone answers this soon.

  • I upgraded to a new apple mac book pro and now when I try to download to adobe digital edition I receive this error:Error getting License. License Server Communication Problem: E_ACT_NOT_READY

    I upgraded to a new apple mac book pro and now when I try to download to adobe digital edition I receive this error:Error getting License. License Server Communication Problem: E_ACT_NOT_READY

    What does that have to do with Digital Publishing Suite?
    We’d love to help but if does have something to do with it, please give us
    some details.

  • "Error getting license. License server communication problem. E_IO_CANNOT OPEN".

    When I download ebooks from libary, I get "Error getting license. License server communication problem. E_IO_CANNOT OPEN". What can I do?

    You may be experiencing an authorization error, see KB: http://helpx.adobe.com/digital-editions/kb/error-e_act_not_ready.html
    Or you may be experiencing a network related problem like the one I'm having:
    http://forums.adobe.com/thread/1420854?tstart=0

Maybe you are looking for

  • Problem in accessing client database.

    hi I have created a application using MDW.I am getting the Client database created.but i donno how to access those tables on client machine by using command prompt.I just wanna see whether those tables had all the data.So plz tell me the Solution. Ed

  • How to test if a decimal is even or odd in labview

    i made a VI that tests for even and odd integers using the quotient/remainder function and the Select function but when i test a decimal it does not work properly. i have my VI testing to see if the input diveded by 2 gives you a remainder equal to 0

  • Editing session gets canceled

    I am starting an editing session programmatically, so clicking outside of the cell being edited does not stop the session. But even when I have resizableColumns="false" sortableColumns="false" if I move a mouse with a left button down over a column s

  • Using two conditions in redered attribute

    I have a link which should be rendered on fulfilling a particular condition which is mentioned in below code. But unfortunately the link is not rendered. <h:outputLink value="/msqcdo/clause24.jsp" title="Previous" rendered="#{appl.apptype=='Manufactu

  • Problems with embedding swfs into Director 11.5

    Hello everyone, I am hoping someone can help me and please bear with me - I don't know a lot about director - I can do some Lingo and get around in the program to make things work. Right now I am working on an interactive presentation where the user