Java WD and Socket Communication

Hi,
Is it possible to use Java Socket Communication with Java Web Dynpro. Or if not what is the best approach to have a Java Socket program integrated with a Web Dynpro Communication.
Basically, I have an application which provides API for communication via Java Sockets.And this needs to be integrated in our SAP application.
Thanks,
CD

Hi,
You are currently using JCO to "Connect to a Remote System" - JCO will connect to a back-end with the main purpose of "executing BAPI's" in it.
When you move to WebDynpro, you have what SAP calls Adaptive RFC Model - this will create a "Model Entity" in you WD Project that will do the same thing your JCO does.
Assume your JCO now calls "BAPI_GET_FLIGHTS", to return the Flights that are currently available - In your newly create WDP Project, you will manually specify what back-end you wanna use when "Importing" and you will tell also the BAPI name. WDP will generate the class structure that you need in order to execute that function.
JCO is what SAP created to execute BAPI's. JCO can be used by any "Java" like application that needs to connect to the back-end. But when you move to WDP, you don't need to use this anymore - You will use WDP Models.
Youi will still need your JCO Destinations created in the Application Server, so behind the scenes WDP creates a "layer" so you don't need to code the JCO calls manually.
Regards,
Daniel

Similar Messages

  • Java Swing and Socket Programming

    I am making a Messenger like yahoo Messenger using Swing and Socket Programming ,Multithreading .
    Is this techology feasible or i should try something else.
    I want to display my messenger icon on task bar as it comes when i install and run Yahoo Messenger.
    Which class i should use.

    I don't really have an answer to what you are asking. But I am developing the same kind of application. I am using RMI for client-server and server-server (i have distributed servers) communication and TCP/IP for client-client. So may be we might be able to help each other out. My email id is [email protected]
    Are you opening a new socket for every conversation? I was wondering how to multithread a socket to reuse it for different connections, if it is possible at all.
    --Poonam.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem with Java Proxy and Socket Connection

    Hi Gurus!!
    I have developed a Java Proxy that connects via socket with a Server Socket application. This Server Socket application accepts more than one connection at the same time.
    When I connect the first time from my Java Proxy, the connection is correctly established. When the first connection opened, if a try a second connection, this is not established.
    I use "new Socket(SocketServer,SocketPort);" to open the connection.
    I think that all time the Java Proxy is trying to open the same connection, and this is a problem.
    Is there a way to indicate to the server that is a new connection and that the existing connections remain?
    Anybody could help me, please?
    Thanks and regards,
    Manuel Míguez.

    Sorry!!!!i must give you more information.
    The error which i have when i push the submit button is
    HTTP Status 404 -
    type Status report
    message
    descriptionThe requested resource () is not available.
    GlassFish Server Open Source Edition 3.0.1
    My thought is that the error is in this line
    String connectionURL = "jdbc:mysql://localhost/mybooking";in mysql when i write this code then the table opens with no problems:
    mysql>show databases;
    mysql>usebooking;
    mysql>showtables;
    mysql>describe booking;Furthermore i have added in my web application the library mysql JDBC driver my-sql-connector-java-5.1.6.bin.jar
    Edited by: 813355 on Nov 22, 2010 1:50 AM
    Edited by: 813355 on Nov 22, 2010 2:00 AM

  • Java NIO and sockets in 1.4.1FCS

    Hi,
    I have built a client server system using the new 1.4 java.nio packages. In 1.4 everything worked fine, yet in 1.4.1 FCS it definitely does not. The process is as follows.
    Everything work in non-blocking mode:
    - Server receives connection and accepts it, the new SocketChannel is put in non-blocking mode and registered with the same selector as the server.
    - New SocketChannel waits for data from the client so it waits for OP_READ from the selector. All it gets is OP_WRITE, OP_CONNECT. With 1.4 it received OP_READ, OP_WRITE.
    I tried adding a call to finishConnect, but that didn't help.
    Anyone have any thoughts about this?
    Thanks,
    Mike.

    The code in the bug report is incorrect. The key will of course always be writable if you do not write anything to the socket! And since it is writable the readable part of the code will never be executed (its in an else-statement). When you are not interested in the OP_WRITE, change the ops on the selection key.

  • Socket communication failure between Java applet and C++ application

    I have a java applet that connects to a C++ application via Java's ServerSocket and Socket objects. THe C++ application is using the Winsock 2 API. The applet and application are running on an NT workstation (SP 6) and using IE (5.5) For a very simple C++ test applications the communictions work fine. Once more code gets added to the C++ application the portion of the socket that C++ listens to seems to close. Upon performing a recv call the return value is a zero. Microsoft insists this is a sign the Java side has shut down the socket. The Java applet can still receive messages from the C++ app but C++ cannot receive responses from the Java side. Java throws no exceptions and an explicit check of the socket shows no errors. Again, what puzzles me is that it works for simple C++ applications. Are there any known conflicts between Java and C++ in this regard?
    I have inlcuded the basic java code segments below.
    / run Method.
      * This method is called by the Thread.start() method. This
      * method is required for the implementation of the Runnable interface
      * This method sets up the server side socket communication and
      * contiuously loops looking for requests from a external
      * socket.
      * @author Chris Duke
      public void run(){
         // create socket connections
         boolean success = false;
         try {
             cServerSocket = new ServerSocket(cPortID);
             System.out.println("Waiting for client to connect...");
             cClientSocket = cServerSocket.accept();
             System.out.println("Client connected");
             // Create a stream to read from the client
             cInStream = new BufferedReader(new InputStreamReader(
               cClientSocket.getInputStream()));
             // Create a stream to write to the client       
             cOutStream = new PrintWriter(
               cClientSocket.getOutputStream(), true);
             success = true;
         }catch (IOException e) {
             System.out.println("CommSocket:Run - Socket Exception(1) " + e);
             success = false;
         // if the socket was successfully created, keep the thread running
         while (success){
             try{
                // check socket to see if it is still available for reading
                if (cInStream != null && cInStream.ready()){
                    // check for an incoming message
                    String message = ReceiveMessage();
                    // Send message to listeners
                    Event(message);
                if (cInStream == null){
                    success = false;
                    System.out.println("CommSocket:Run - shutdown");
             }catch (IOException e){
                System.out.println("CommSocket:Run - Socket not ready exception");
                break;
    // SendMessage method -
      *  Sends a text message to a connected listener through port specified by portID
      * @author Chris Duke
      * @param  String message - This will be the message sent out through the server
      * socket's port specified by portID.
       public void SendMessage(String message){
          cOutStream.println(message);
          if (cOutStream.checkError() == true)
            System.out.println("SendMessage : Flush = Error");
          else{
            System.out.println("SendMessage : Flush - No Error");
       }

    a very simple C++ test applications the communictions work fine. Once more code gets added to the C++ application the portion of the socket that C++ listens to seems to close.
    This quite strongly implicates the extra code in the C++ App. The firstly thing I would try would be telnet. Try connecting to both versions of the C++ Application and manually reproducing a proper exchange.
    a recv call the return value is a zero. Microsoft insists this is a sign the Java side has shut down the socket.
    A correct implementation of recv should return the number of bytes received, or -1 for an error. A zero return indicates no bytes received not a socket closed/error. This sounds like FUD to me.
    Are there any known conflicts between Java and C++ in this regard?
    I can see no obvious faults, though the code is incomplete, I don't think it's an sockets implementation issue, at either end, it sounds more likely to be a protocol/handshaking bug in the C++ App.

  • Error in the Socket Communication between Java Client and VC++ Server

    In my application, using Java Client to do socket bi-communication with VC++ Server, which is done by somebody else.
    The error is after the application properly running one or two days, the VC++ Server cannot receive the messages passed by java Client, but at Java client, everything is the same, although using CheckError() after every print(), there is no exception thrown.
    The JVM is jdk1.3.1, platform is Win2k Server.
    The outputstream is PrintWriter().
    Please help me to settle down this problem. Thanks in advance.

    I read some thread in the forum, and found somebody had the similar problem with me. Just want to know how to settle this problem.
    In the client/server program. Client is a JAVA program and Server a
    VC++ program. The connection works, and the problem appears after some time. The Client sends a lots of requests to Serverm, the server seems receive nothing. But at the same time, the server is able to send messages to Client. The Client also can get the messages and handle them. Don't understand why there this problem and why it appears when it wants.
    The client is a Win2k platorm with JDK1.3.1 and the server is also a Win2K platform with VC++ 6.0.
    In the Client, using:
    inputFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    outputToServer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
    Hope can get your help.

  • Socket communication between Java and Python aplications.

    I'm try to connect a pyhton client to a Java server through Socket. The problem is that the python client never receive anything. I'm using a ObjectOutputStream to send the msgs. Does anyone have any idea how make this works?!

    RicardoS wrote:
    So how do you do it?! What do you use?!Bytes! Normally I generate the bytes from XML.
    Edited by: sabre150 on Mar 24, 2008 5:10 PM

  • Socket communication between client and server

    Hi all,
    I am doing an assignment for communication between java client and java server using sockets. This communication is in the form of XML documents. I am facing a problem in this communication.
    Actually at Server side I'm creating an XML document(Document type object) using DocumentBuilderFactory in javax.xml.parsers package and transforming this Document into a stream using StreamResult.
    My code is :
    Transformer xmlTransformer = TransformerFactory.newInstance().newTransformer();
    StreamResult xmlString = new StreamResult(currentClientHandler.getSocketOutputStream());
    DOMSource xmlDocSource = new DOMSource(xmlDocument); // xmlDocument is Document type reference
    xmlTransformer.transform(xmlDocSource, xmlString);
    so, this xmlString(i.e. StreamResult) is passed directly into the output stream. Here I need to close() output stream after transform() call to help SAX parser to know about end of stream.
    Now at Client side, I am parsing this stream using SAX parser. It parses this correctly. But when sending some another data back to Server when client opens output stream, it given Socket closed exception. I know that closing input or output stream closes socket. But in my problem, I have to send data in streams and not by using files or byte[] etc.
    So what is nearest solution to problem ??
    Plz help me. Any kind of help will be greatly appreciated.

    hi
    thanks for ur reply.
    I didnt get any error msg while getting the back the datas.
    Actually i divided my application into two parts.
    My application will act as both server and client.
    server ll get the browser request and send to the client and the client will send that data to the c++ server.
    Im able to do that.and unable to get the data from server.
    Didnt get any error.
    can u tell me how to make an application to act as both client and server.
    I think im wrong in that part.
    thanks a lot

  • Use of synchronized queue for java socket communications

    Hi all,
    We have a need for a server socket application (stand alone java application) to process just one command per time coming from a java socket client (JSP Web application). There are a lot of users accessing the java socket client, but the server socket can only handle one command per time, so there is a need of a queue type, so users will have to wait for their time.
    We've been told that we can use "synchronized Queue", but we don't know what it is and how to use. A URL, book etc. with sample code would assist us, since we are new to both java socket communication and queue of commands.
    Can anyone assist us
    cheers
    Trajano
    P.S.
    The server socket java application has two threads:
    1st thread handles the java socket communication;
    2nd thread is a RS-232 serial driver that communicates to several micro-controllers connected on a multi-drop.
    JSP web app client socket users can issue various commands at the same time to the java server socket app, however the server can only service one command per time (just one RS-232 COM1 serial port available). The commands have to somehow be added to a queue for processing.

    I do not have the experience to offer advice. But I just happened to be reading today about Collections.synchronizedList.
    import java.util.List;
    import java.util.LinkedList;
    import java.util.Collections;
    public class Queue {
       private List queue;
       public Queue() {
          queue = Collections.synchronizedList(new LinkedList());
       public Object removeItem() throws InterruptedException {
          synchronized (queue) {
             while (queue.isEmpty())
                queue.wait();
             return queue.remove(0);
       public void addItem(Object item) {
          synchronized (queue) {
             queue.add(item);
             queue.notifyAll();
    class Test {
       public static void main(String[] args) {
          final Queue queue = new Queue();
          //start a thread to process items from the queue
          Runnable work = new Runnable() {
             public void run() {
                try {
                   Object item = queue.removeItem();
                   //do something with item
                } catch (InterruptedException e) {
                   //handle this
          Thread worker = new Thread(work);
          worker.start();
    }Reference: Java Thread Programming, Paule Hyde
    Also, here is Doug Lea's library,
    http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html

  • 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.

  • 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 :)

  • Using thread and socket connection with other machines

    Hi all!
    we are using weblgoic 5.1 SP9 JDK1.2.2
    we already using java.net.Socket and java.lang.Thread
    to communication TANDEM Machine on the weblogic.
    the reason why we use to socket and thread even though it is not
    recommanded is that below
    1. once we connect Socket, then we using until server shutdown or
    connection may has the problem, so we're using thread to wait
    java.io.Inputstream to read from socket.(if I using EJB, It can't
    wait socket inputstream indefinetly, because it has timeout)
    2. we're logging Database date sent or received with TANDEM Machine.
    so we need Database Access. so we using Database Access
    thru Weblogic.
    3. EJB Application using (other EJB Application - send Module)
    to send data to TANDEM Machine. So "Send Module" should
    be implemented EJB.
    but. Now I see there might be problem this framework.
    so, is there some way by just using J2EE spec, to implement this kind of
    framework.
    wait for your great help !!
    regards.

    Yes i've tried interrupt method and it doesn't have any effects on the thread... it stay in connect() method...
    And for the timeouts, in fact i use an API : J2SSH, to connect with SSH protocol, and the setting of connection timeouts is not implemented yet... and the default timeout is about 4 minutes...
    so i don't know how to solve this problem...

  • How to manage socket communications

    i need to learn about how to manage socket communications. does any one has sample codes to share that illustrates how to manage sockets? Im going to create an application that listens over a socket. My socket listener should be able to read over the socket continuously without user intervention. If there's no data, it would wait until something comes in. If some data come in, the listener should be able to read it automatically, and save data in db.
    Im thinking of an infinite loop here, but the problem
    arises when the socket is waiting for data to come in. The application consumes 100% CPU resources. And im only running one instance of my socket listener. My solution here is to use threads and let the thread SLEEP for a while when no there's no data yet.
    Any advise on this matter is very much appreciated. Thank you.

    It sounds, that you are using non-blocking read from a socket inside a busy wait loop. You should do a blocking read, which means your process/thread will be suspended by OS untill something is available on your socket.
    I'm new to Java and I can not say how actually to implement this, but look for "blocking/non-blocking read" in network interface documentation.
    Zhenya.

  • Socket Communications

    Socket communications over http-proxy.
    Is this a failure of Sun Java?? Its an useful and compulsury nessacity for java programmers.
    Any help is accepted

    Thanx for your early advice. But I did the same what you told. It works fine with URLConnections.
    But I'm using java.net.Socket and java.net.ServerSocket.
    I need to use this plain socket for my communications. But connections over this socket with http-proxy fails.
    Any help is welcomed..........

  • How to interchange data between Java Program and C++ Program

    I constructed a java program using netbeans IDE that has ability to connect with a respective DLL; I want to connect and interchange data between my java program(.jar) and VSC++ program(.exe) through DLLs.JNI uses single Dll to invoke C/C++ function in native manner,In order to increase the efficiency I tried to connect and interchange primitive data types between Java program and C++ program using that DLL(JNI implemented).
    Unfortunately C++ program cannot obtain data values that has been changed by Java Program.For example - If I declare a global int variable in DLL,java program can catch that int variable and can update it but If I run my C++ program(exe) loading same DLL simultaneously it cannot receive the updated value of that int variable declared in the DLL.
    Therefore I need a solution to share/Interchange at least primitive data and their respective values between a JAVA and C++ Program using JNI (in spite of date transferring through Sockets).JAVA TO C/C++ & C/C++ to JAVA using DLLs.
    (TWO WAY COMMUNICATION)
    JAVA.jar  <=> <JNI> <=> DLL <=> [Connector Program C/C++] <=> C/C++ .exe
    PLEASE HELP ME!! THANK YOU

    What in the are you trying to say? What does "filled into the servlet mean?" Is the map somewhere outside the servlet? In a different process? Are you asking how to extract data from a map? Something else?
    Sorry, but your question makes no sense.

Maybe you are looking for

  • DWCS3 takes a long time to open!

    HI, As you read on the title, DW CS3 for Mac Leopard is taking a long time to open. When you click on the application to open the program, you get the typical DW green screen, the version # (9.0 Build 3481) but below that, all that stuff that read as

  • External Hard Drive is read only?? how do i change this?

    ive just gotten a new external hard drive which i use a giant usb pretty much, only problem is when i drag files into it to copy it tells me that "untitled" cant be modified.. also when i check its info im told that it is read only... how do figure o

  • How to use database look up table function in xsl mapping

    Can anybody tell me how to use database look up table function while mapping xsl between 2 nodes. I have an XML file coming in and depending on one of XML elements we need to decide which further path to take. But, using this XML element, we need to

  • Error in Synchronizing Slave Repository

    Hi All, I've created a Master / Slave pattern and when i make any changes in the Master and Synchronize the slave i get the following error: <b>"Unable to retrieve synchronization data from master repository. See the Assertion Log for more informatio

  • AS2 setup -- AS2Receive Pipeline

    Hi, We have AS2 set up for communicating with some parties. For receiving the AS2 messages a HTTP receive location is configured, it uses AS2Receive and AS2Send pipeline. I want to know how does AS2Receive pipeline decrypts the incoming message? How