Servlets & Sockets

Hi,
Thank you for your replies to my earlier problem.I am creating a servlet for a school project.The servlet is supposed to be used for an online library.This is just a project to test Java Servlet principals.Once i create the servlet ,do I need to specify the "sockets"?I actually will not be using this online ,as this is a small project.The whole system should run within the PC itself.In such a scenario, would i need to use the java.net package at all??How do you process "POST" requests from htmls?(eg:A user "posts" a txt file with all his/her user details to the servlet,the servlet must take the data ,validate it and input the data into a database).Is the Printwriter the best way for a servlet tocommunicate with an html?What are the other responses?
I also have another problem: In the html (interface) ,The user will navigate from one page to another via the use on buttons within the html webpage.In this case ,would i need to send a request to the servlet on every html-button click?Can i redirect the client's browser using html code only?
Thanks.
Regards,
Aeshan

Hi aesh83,
I am not sure if I am misunderstanding your intentions here or not ...but you don't just run a servlet (or jsp) the way you can double click an html page in a folder. You need a servlet runner (which is like a server of sorts) such as Tomcat (preferred) or jswdk (simple and limited ...does not process POST). There are others as well, but these are a few of the common choices. You may or may not have success getting your school to install these on their system. My school was pretty picky about this ...and the answer was always a flat out 'NO'. Once you have a servlet runner installed and running ...and in your case a database as well ...you can begin creating servlets to do what you desire.
You don't really do anything special to process POST or GET requests beyond building a proper servlet. But the key is that they must be deployed in one of these special servers. I hope I didn't misunderstand your post, but it seemed like you assumed you could double click an html on the local file system, and viola, in steps your servlet. This is not the case. There are some good tutorials that outline these concepts on this site. Forgive me if I have intuited your post inaccurately.

Similar Messages

  • Communication beween an http client a servlet and a socket server

    Hello I’m developing an application that needs a client to communicate with a servlet using Http and then the servlet needs to connect to a server using sockets.
    The client will send an image to the servlet and then the servlet will send that image to the server.
    Everything works OK except when I try to send the data from the servlet to the server. It seems that there is no indication of when the outputstream has reached its end. So when trying to do this at the server side:
    BufferedInputStream inFromClient =
                  new BufferedInputStream(serverSocket.getInputStream());
    int inp=0;
    while ( (inp=inFromClient.read())!=-1 )
             //do smth
    }The server will block at the read() method.
    If I close the connection from the servlet using the close() method of a print stream everything will work fine
    but I don't want to do that because I want the server to send a message back at the servlet.
    I don't know if I make any sense but I'm new to servlets and Java as well.
    Thanks in advance and if there something that you don't understand please let me know.

    I'm not quite sure what you mean. I have tried to do the same in the following piece of code and it worked fine. The only difference is that here the data is read from a file but I still send it as raw data(bytes).
    import java.io.*;
    import java.net.*;
    public class Client
        private String path="c:\\img0049.jpg";
        private static void sendImage(Socket client,BufferedOutputStream toServer)
             BufferedInputStream readFile=null;        
             int inp=0;        
             try
                  readFile = new BufferedInputStream( new FileInputStream(path) );
                  while ( (inp=readFile.read())!=-1 )
                        toServer.write(inp);
              catch (IOException e)
                   e.printStackTrace();
              finally
                if (readFile != null)
                     try {
                   readFile.close();
              } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                     //client.close();
        public static void main(String args[]) throws Exception {
            // connect through localhost to the same port that the server is listening to
            Socket clientSocket = new Socket("127.0.0.1", 4322);
            BufferedOutputStream outToServer =
                    new BufferedOutputStream(clientSocket.getOutputStream());             
                sendImage(clientSocket,outToServer);              
            outToServer.close();
            clientSocket.close();
        }// main   
    }// classIn the server side I'm just reading it with something like that
    try {
                    BufferedOutputStream out =
                         new BufferedOutputStream( new FileOutputStream("c:\\out.jpg"));
                    int inp=0;
                    while ( (inp=inFromClient.read())!=-1 )
                         out.write(inp);
                    out.close(); //close will also flush
    //.....rest of codeNow here is the servlet code of the application that I'm discussing (the servlet has already received the data from the client using the Htpp protocol. I know it has through debugging).
    I'm guessing that the servlet is storing my data in the BufferedInputStream so then I'm trying to read from there and send it to the server
    public void doPost(HttpServletRequest request, HttpServletResponse response)
                   throws IOException, ServletException
              /* Get input stream from mobile client: Servlet<-- Client */
              ServletInputStream inputFromClient = request.getInputStream();
              BufferedInputStream bufInputFromClient = new BufferedInputStream(inputFromClient);
              /*Create socket and get output stream in order to communicate with
               * Server: Server<-- Servlet */
              Socket clientSocket = new Socket("127.0.0.1",4322);
              OutputStream outputToServer = new PrintStream(
                        clientSocket.getOutputStream());
              /* Empty buffer and send data to output stream */
              int inp=0;          
                         while ( (inp=bufInputFromClient.read())!=-1 )
                          outputToServer.write(inp);
                        outputToServer.flush();                   
                       //outputToServer.close(); //If I use this the server will know that the stream has ended                   At the server I'm using again the 2nd piece of code I posted above.
    That's it I hope I'm not confusing you.Thanks

  • How to make a socket connection timeout infinity in Servlet doPost method.

    I want to redirect my System.out to a file on a remote server (running Apache Web Server and Apache Tomcat). For which I have created a file upload servlet.
    The connection is established only once with the servlet and the System.out is redirected to it. Everything goes fine if i keep sending data every 10 second.
    But it is required that the data can be sent to the servlet even after 1 or 2 days. The connection should remain open. I am getting java.net.SocketTimeoutException: Read timed out Exception as the socket timeout occurs.
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.
    Following is the coding to establish a connection with the Servlet.
    URL servletURL = new URL(mURL.getProtocol(), mURL.getHost(), port, getFileUploadServletName() );
    URLConnection mCon = servletURL.openConnection();
    mCon.setDoInput(true);
    mCon.setDoOutput(true);
    mCon.setUseCaches(false);
    mCon.setRequestProperty("Content-Type", "multipart/form-data");
    In the Servlet Code I am just trying to read the input from the in that is the input stream.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    byte [] content = new byte[1024];
    do
    read = in.read(content, 0, content.length);
    if (read > 0)
    out.write(content, 0, read);
    I have redirected the System.out to the required position.
    System.setOut(........);
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.

    I am aware of the setKeepAlive() method, but this can only used with the sockets. Here i am inside a servlet, have access to HTTPServletRequest and HTTPServletResponse and I don't know how to get access to the underlying sockets as the socket handling will be handled by the tomcat itself. If I am right there will be method in the apache tomcat 6.0.x to set this property. But till now I am not getting it.

  • How can servlet serve more than one client's socket links when tomcat start

    I have done this in the servlet's 'init' method:
    while (true)
    Socket sk = server.accept ();
    new ServerThread (sk).start ();
    but tomcat STOPPED at this point! The webapp didnot even been installed. But I want to show the index.jsp pages of the webapp, the code above only running at background. How can I do that?

    Eeeew... what are you doing there? Of course Tomcat stops. You have an infinite loop, and accept() blocks until someone actually connects.
    And a servlet shouldn't be using sockets anyway. This is most ugly, and possibly against the J2EE specs.

  • BEA-101083 Connection failure.java.io.IOException: A complete message could not be read on socket: 'weblogic.servlet.internal.MuxableSocketHTTP@16907c  at weblogic.socket.SocketMuxer$TimeoutTrigger.trigger

    While trying to publish mesaage by MQ 5.3 .I got the following error
              Please help.
              <Error> <HTTP> <BEA-101083> <Connection failure.
              java.io.IOException: A complete message could not be read on socket: 'weblogic.servlet.internal.MuxableSocketHTTP@1c94ff
              3 - idle timeout: '30000' ms, socket timeout: '30000' ms', in the configured timeout period of '60' secs
              at weblogic.socket.SocketMuxer$TimeoutTrigger.trigger(SocketMuxer.java:775)
              at weblogic.time.common.internal.ScheduledTrigger.run(ScheduledTrigger.java:243)
              at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:317)
              at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:118)
              at weblogic.time.common.internal.ScheduledTrigger.executeLocally(ScheduledTrigger.java:229)
              at weblogic.time.common.internal.ScheduledTrigger.execute(ScheduledTrigger.java:223)
              at weblogic.time.server.ScheduledTrigger.execute(ScheduledTrigger.java:49)
              at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
              

    Can you help me ? I have the same problem.

  • Servlet/applet/socket problem

    Hi there,
    my problem is this...
    i create a page with an servlet whicht shows an applet. this applet connects to a server through an socket. it works fine, but, when i change the page and the applet is not longer on the screen, the socket connection will be not killed! i dont know why. but i must kill it when the applet is not longer on the screen...whats wrong? can you help me?
    matthias

    Are you overriding the destroy() method in your Applet? This will be called when the applet is about to be unloaded from the browser. Or, as a slightly different alternative, you can override the stop() method, which is called when the applet is scrolled off the screen. Usually when stop() is used, start() is overriden as well to allow the applet to resume when it is scrolled back into view. For more info, read up on the applet lifecycle.

  • Communicating C or C++ sockets with Servlet

    Hi,
    Can any tell me how can we communicate with a C or C++ socket. The following is the Scenario
    A C++ normal socket will send a request (GET) via http. The requested info is processed and the servlet should send back the data without opening a client socket in servlet. Since Web server will itself acts a socket?
    Can we send data back to the C++ socket from servlet???
    Please let me know ASAP
    Thanks

    Hi Arun,
    thanks your reply. I may have not communicated properly. Here is the detailed explaination of the problem.
    We have a embedded VC++ application running WindowsCE OS and an java Socket server with 4444 lisenting port running WindowsNT workstation. The WindowsCE application has three buttons connect , send and disconnect.
    Java socket server is running and we click on the connect button. The first point communication is complete with both doing hand shaking. But i did not receive data on event of Send (Click event of a button). But on closing the WindowsCE application or clicking disconnect button i received the raw data with some junk values. While sending data i had ensured that from WindowsCE is received in the same format on java side i.e., UTF-8 format
    Please let me if you have a solution
    Regards,
    Venkatesh

  • Applet-Servlet communication in RMI or sockets

    As a dissertation piece I am creating a game to be played by multiple players accross the internet using servlets. However I am having great difficulty figuring out how to use RMI or sockets within servlets (I already have the socket-based code). I also can't seem to find many books or sites out there which might help. If anyone outthere has done this type of thing before or can advise any reading material I would be very grateful

    Write a servlet and in the web.xml have the servlet load on server start-up.
    In the servlet have a thread start in the init method. The thread will start a socket server that the applets can connect to. The socket server can be the standard socket server as outlined in the tutorial:
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • Servlets or EJB for Persistent external socket connections

    We have a Servlet that establishes a socket connection to another
    external server and sends and receives messages. We have the Servlet defined as pre-loaded when JRun starts.
    When JRun is started, the Servlet is started and connection is
    established with the external server. The problem is when a new message is being sent, the Servlet is instantiate again and the connection is stopped and restarted. We do a forward request from another Servlet to this.
    Am I totally misunderstanding Servlets because reading articles
    and books seems to indicate that I should create an EJB instead of a
    Servlet if you want a persistent connection.
    Thanks in advance for your help.

    I assume then that your connection to the external server is achieved in the "init" method of your servlet. Therefore every time the servlet container is called upon to accesss your servlet, it instantiates it - thus a new connection will be being made each time.
    I would take out the connection properties from the init method. I.e. you only want it to happen once.
    T

  • How to check whether socket or servlet mode?

    HI
    What are the various ways to check whether forms server is in socket mode or servlet mode.
    Thanks
    JIL

    You can check context file also
    you can confirm form server is set at servlet mode by
    -bash-3.00$ grep s_frmConnectMode $CONTEXT_FILE
    <forms_connect oa_var="s_frmConnectMode">servlet</forms_connect>
    -bash-3.00$
    socket mode by,
    -bash-2.05b$ grep socket $CONTEXT_FILE
    <forms_connect oa_var="s_frmConnectMode">socket</forms_connect>
    -bash-2.05b$ grep
    Suresh
    http://applicationsdba.blogspot.com

  • Send Host name by socket? in servlets

    Hi !
    how to send request with out Host Name, is it possible ?.
    like : http:///servlet/Sample .
    send Host Name by socket programming(may be in c or c++).
    if yes,how to communicate with that socket.
    Please Help me.
    Thanks in advance,
    vij.

    Hi Nitin,
    Following is the specification for getRemoteHost()
    "Returns the fully qualified name of the client that sent the request, or the IP address of the client if the name cannot be determined. For HTTP servlets, same as the value of the CGI variable REMOTE_HOST." I think the same would be true for getHostName().....
    So, this can be one possiblity why ur given IP.

  • 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

  • AccessControlException when establishing socket connecion within servlet

    Hello good people!
    I need to use a socket connection within the function doGet() of HttpServlet.
    The code is as following:
    public void doGet (HttpServletRequest request,
              HttpServletResponse response) throws ServletException, IOException
         Socket socket;
         OutputStream outStream;
         InputStream inStream;
         String transID;
         PrintWriter out = null;
         transID = request.getParameter("transID");
         try
              out = response.getWriter();
    response.setContentType("text");
              //creation and connection of socket.
              socket = new Socket("147.161.2.170", 7665);
    outStream = socket.getOutputStream();
              inStream = socket.getInputStream();
              outStream.write(transID );
              byte[] locRes = new byte[ANSWER_SIZE];
              int readSize = inStream.read(locRes);
              locStr = new String(locRes, 0, readSize);
              out.println("hello");
         catch(Exception e)
              out.println(e.getMessage() + " " + e.toString());     
    Lhe line "socket = new Socket("147.161.2.170", 7665);" causes an Exception which is caught in the catch clause, and as result I get the following:
    access denied (java.net.SocketPermission 147.161.2.170:7665 connect,resolve) java.security.AccessControlException: access denied (java.net.SocketPermission 147.161.2.170:7665 connect,resolve)
    What's its problem??
    Is there any problem in establishment of socket connection within a HttpServlet?
    Please help, all of you!
    Thanks beforehand

    someone hears me???
    help!!!

  • Send email from j2me through servlet

    Hi people,
    i hope you can help me because i am new in network programming.
    I am trying to send email from j2me to googlemail account I have 2 classes EmailMidlet (which has been tested with wireless Toolkit 2.5.2 and it works) and the second class is the servlet-class named EmailServlet:
    when i call the EmailServlet, i get on the console:
    Server: 220 mx.google.com ESMTP g28sm19313024fkg.21
    Server: 250 mx.google.com at your service
    this is the code of my EmailServlet
    import java.io.*;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.text.*;
    import java.util.Date;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class EmailServlet extends HttpServlet {
       public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
          System.out.println("____emailservlet.doPost");
          response.setContentType("text/plain");
          PrintWriter out = response.getWriter();
          System.out.println("______________________________");
          out.println();
          String to = request.getParameter("to");
          System.out.println("____________________________to" + to);
          String subject = request.getParameter("subject");
          String msg = request.getParameter("msg");
          // construct an instance of EmailSender
          System.out.println("servlet_to" + to);
          send("[email protected]", to, subject, msg);
          out.println("mail sent....");
       public void send(String from, String to, String subject, String msg) {
          Socket smtpSocket = null;
          DataOutputStream os = null;
          DataInputStream is = null;
          try {
             smtpSocket = new Socket("smtp.googlemail.com", 25);
             os = new DataOutputStream(smtpSocket.getOutputStream());
             is = new DataInputStream(smtpSocket.getInputStream());
          } catch (UnknownHostException e) {
             System.err.println("Don't know about host: hostname");
          } catch (IOException e) {
             System.err
                   .println("Couldn't get I/O for the connection to: hostname");
          if (smtpSocket != null && os != null && is != null) {
             try {
                os.writeBytes("HELO there" + "\r\n");
                os.writeBytes("MAIL FROM: " + from + "\r\n");
                os.writeBytes("RCPT TO: " + to + "\r\n");
                os.writeBytes("DATA\r\n");
                os.writeBytes("Date: " + new Date() + "\r\n"); // stamp the msg
                                                    // with date
                os.writeBytes("From: " + from + "\r\n");
                os.writeBytes("To: " + to + "\r\n");
                os.writeBytes("Subject: " + subject + "\r\n");
                os.writeBytes(msg + "\r\n"); // message body
                os.writeBytes(".\r\n");
                os.writeBytes("QUIT\r\n");
                // debugging
                String responseLine;
                while ((responseLine = is.readLine()) != null) {
                   System.out.println("Server: " + responseLine);
                   if (responseLine.indexOf("delivery") != -1) {
                      break;
                os.close();
                is.close();
                smtpSocket.close();
             } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
             } catch (IOException e) {
                System.err.println("IOException: " + e);
       } 1.when i print "to" in EmailServlet also:
      String to = request.getParameter("to");
          System.out.println("____________________________to" + to);  it show null on the console :confused:
    2. ist this right in case of googlemail.com?
      smtpSocket = new Socket("smtp.googlemail.com", 25);  I would be very grateful if somebody can help me.

    jackofall
    Please don't post in old threads that are long dead. When you have a question, please start a topic of your own. Feel free to provide a link to an old thread if relevant.
    I'm locking this thread now.
    db

  • Using socket or CGI for report generation

    I have a 100+ c executables(.exe) which accepts arguments and will generate report.These executables lies in a linux server. Through my web application, based on the functionality i need to invoke these .exe and have to generate the report.
    I am using JSF/servlet to generate the query string(i.e. exe name with its relevant parameters).
    I have two option to do the same.
    1. Through socket programming send the request from client(JSP) to linux server that accepts the input and it process the request and send the report back.
    2. Send the request from client web browser(JSP) running in JBOSS to the apache web server via CGI and it execute the exe and generate the report.
    could you let me know which is the efficient way of generating the report. If there is any other option let me know.

    It's more that there is no disadvantage in your case. The usual objection to CGI (and indeed one reason why we have servlet containers at all) is that you have to start a new process per request, but you have that problem anyway because of your hundreds of C programs.

Maybe you are looking for

  • My iPod isn't recognized by iTunes and I want to update it but I can't. What do I do?

    I plug in my iPod and it will charge but I have tried everything to get iTunes to recognize it and it won't. I want to update it to IOS 5 but I need the iTunes to connect with it.

  • 3 tier mode in BO 4.0

    Hi all ! How I can connect to server from client pc at  Interactive Analysis in 3 tier mode? Like server:6400(J2EE Portal). In R3 i create deski document in infoview to generate this type of connection. thanks!

  • Can any one help me to solve my prblem

    exception java.io.IOException is never thrown in body of corresponding try statement import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; import java.util.Date; import java.io.*; public class SampleIO2 int[] u=

  • Uninstall SAP Addon

    Hi Basis Experts, Can any one tell me How to uninstall a SAP addon/component? Appreciate your time and help Thanks CG

  • How to extract data from MS-Access

    Hi Experts, I have a scenario where I have to extract data from MS-Access. I'm developing a ABAP component. I looking for help in writing query for data extraction. I have no idea of extracting data form MS-Access. Have worked on BAPI and SAP tables