Help! question about socket

I set up a client socket (port 80) connected to the webserver which is using apache 1.3.14. Then I used the following code:
Writer out=new OutputStreamWriter(connection.getOutputStream());
out.write("GET /head.html");out.write("\r\n");
out.flush();
InputStream raw=connection.getInputStream();
BufferedInputStream buffer=new BufferedInputStream(raw);
InputStreamReader in=new InputStreamReader(buffer);
int c;
while((c=in.read())!=-1) {System.out.write(c);}
It is OK until now. But when the client finished receiving the file, the socket seemed to be closed automatically. I do not know what happened to that. Please tell me how to make the socket available and usable after that? Thanks.

I think I get it. Use this code:
Writer out=new OutputStreamWriter(connection.getOutputStream());
out.write("GET /menu.html HTTP/1.1");out.write("\r\n");
out.write("Host:"+hostname);out.write("\r\n\r\n");
out.write("GET /head.html HTTP/1.1");out.write("\r\n");
out.write("Host:"+hostname);out.write("\r\n\r\n");
out.flush();
InputStream raw=connection.getInputStream();
BufferedInputStream buffer=new BufferedInputStream(raw);
InputStreamReader in=new InputStreamReader(buffer);
int c;
while((c=in.read())!=-1) {System.out.write(c);}
Thank you so much!

Similar Messages

  • I have a question about socket

    I've got a socket question that haven't to work out for two days . If you know something about this question please give me a hand , Thank you .............
    ===================================================
    I want to write a program about PortMapping with Java.
    It means : put one port's data to another port .
    =============================
    Just like :
    There is a Tomcat Web Server listener on the 8080 port, and I want to make a socket that listener on the 9090 port. When the client use the Browse visit my web on 9090 port , this socket will be send this data stream from 9090 port to 8080 port and then the Tomcat Web Server process this data and return the result to client use the 9090 port .
    =============================
    (In order to let this program suit for every model (include c/s and b/s),so I think it must be use the byte[] stream )
    ====================================================
    BinaryPort.java
    package sailing;
    import java.io.*;
    import java.net.*;
    public class BinaryPort implements Runnable
    private ServerSocket listenerSocket;
    private Socket serverSocket;
    private Socket tomcatSocket;
    private Thread myThread;
    private DataInputStream in;
    private DataOutputStream out;
    private ByteArrayOutputStream swapStream;
    public BinaryPort()
    try
    System.out.println("Server is starting ..................");
    this.listenerSocket=new ServerSocket(9090);
    this.tomcatSocket=new Socket("127.0.0.1",8080);
    this.swapStream=new ByteArrayOutputStream();
    this.myThread=new Thread(this);
    this.myThread.start();
    catch(Exception e)
    System.out.println(e);
    public void run()
    while(true)
    try
    this.serverSocket=this.listenerSocket.accept();
    this.in=new DataInputStream(this.serverSocket.getInputStream());
    byte[] buf=new byte[100];
    int rc=0;
    while((rc=in.read(buf,0,buf.length))>0)
    this.swapStream.write(buf,0,rc);
    this.swapStream.flush();
    byte[] resBuf=swapStream.toByteArray();
    this.out=new DataOutputStream(this.tomcatSocket.getOutputStream());
    this.out.write(resBuf,0,resBuf.length);
    this.out.flush();
    //Get The Tomcat Web Server reBack Information
    this.in=new DataInputStream(this.tomcatSocket.getInputStream());
    byte[] buf2=new byte[100];
    int rc2=0;
    this.swapStream=null;
    while((rc2=in.read(buf2,0,buf2.length))>0)
    this.swapStream.write(buf2,0,rc2);
    this.swapStream.flush();
    rc2=0;
    byte[] resBuf2=swapStream.toByteArray();
    this.out=new DataOutputStream(this.serverSocket.getOutputStream());
    this.out.write(resBuf2,0,resBuf2.length);
    this.out.flush();
    this.myThread.sleep(1000);
    this.out.close();
    this.in.close();
    catch(Exception e)
    System.out.println(e);
    public static void main(String args[])
    new BinaryPort();
    ====================================================
    I found that it stop on the first "while" , and I don't know what is the reason .............

    Well , I've got it ~~~~~~~~~
    if the read method hasn't the another data , this method will be stoped . so ..............
    ===============================
    package sailing;
    import java.io.*;
    import java.net.*;
    public class ModifyBinaryPort
         private ServerSocket listenerSocket;
         private Socket serverSocket;
         public ModifyBinaryPort()
              try
                   System.out.println("Server is starting ..................");
                   this.listenerSocket=new ServerSocket(9633);
                   while(true)
                        try
                             this.serverSocket=this.listenerSocket.accept();
                             new MyThread(serverSocket).start();                    
                        catch(Exception e)
                             System.out.println(e);
              catch(Exception e)
                   System.out.println(e);
         public static void main(String args[])
              new ModifyBinaryPort();
         class MyThread extends Thread
              private Socket threadSocket;
              private Socket tomcatSocket;
              private Thread myThread;
              private DataInputStream in;
              private DataOutputStream out;
              public MyThread(Socket socket)
                   try
                        threadSocket=socket;
                        this.tomcatSocket=new Socket("127.0.0.1",9090);
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        //Read Thread
                        new ReadClientWriteTomcatThread(threadSocket,tomcatSocket).start();                    
                   catch(Exception e)
                             System.out.println(e);
         class ReadClientWriteTomcatThread extends Thread
              private DataInputStream read;
              private DataOutputStream write;
              private ByteArrayOutputStream swapStream;
              private Socket threadSocket;
              private Socket tomcatSocket;
              public ReadClientWriteTomcatThread(Socket threadSocketT,Socket tomcatSocketT)
                   try
                        threadSocket=threadSocketT;
                        tomcatSocket=tomcatSocketT;
                        read=new DataInputStream(threadSocket.getInputStream());
                        write=new DataOutputStream(tomcatSocket.getOutputStream());
                        this.swapStream=new ByteArrayOutputStream();
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        byte[] buf=new byte[100];
                        int rc=0;
                        while((rc=read.read(buf,0,buf.length))>0)
                             this.swapStream.write(buf,0,rc);
                             this.swapStream.flush();
                             if(rc<buf.length)
                                  break;
                             //System.out.println(rc);
                        byte[] resBuf=swapStream.toByteArray();
                        this.write.write(resBuf,0,resBuf.length);
                        this.write.flush();
                        //Reading the result from tomcat
                        new ReadTomcatWriteClientThread(threadSocket,tomcatSocket).start();
                   catch(Exception e)
                        System.out.println(e);
         class ReadTomcatWriteClientThread extends Thread
              private DataInputStream read;
              private DataOutputStream write;
              private ByteArrayOutputStream swapStream;
              public ReadTomcatWriteClientThread(Socket threadSocket,Socket tomcatSocket)
                   try
                        read=new DataInputStream(tomcatSocket.getInputStream());
                        write=new DataOutputStream(threadSocket.getOutputStream());
                        this.swapStream=new ByteArrayOutputStream();
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        byte[] buf2=new byte[100];
                        int rc2=0;
                        while((rc2=read.read(buf2,0,buf2.length))>0)
                             this.swapStream.write(buf2,0,rc2);
                             this.swapStream.flush();
                             if(rc2<buf2.length)
                                  break;
                        byte[] resBuf2=swapStream.toByteArray();
                        this.write=new DataOutputStream(write);
                        this.write.write(resBuf2,0,resBuf2.length);
                        this.write.flush();          
                        this.write.close();
                        this.read.close();
                   catch(Exception e)
                        System.out.println(e);
    }==================
    but it still has some little bug , I think I will work out soon .........
    Thanks for your help ejp .............

  • Please help: question about eclipse & xerces

    hi,
    i have eclipse 3.0 and am trying to get the xerces java package (ver 2.6.2) to work for it. i downloaded xerces from this link: http://www.apache.org/dist/xml/xerces-j/
    there are so many different files in there, i'm not entirely sure if you download everything or just one. anyway, the one i downloaded was the fourth one down, called xerces.j.bin.2.6.2.zip (5.6m in size).
    i've unzipped it, but am unsure how i go about configuring eclipse 3.0 so that i can import and make use of xerces in my java apps. could anyone who has experience with this please help me?
    thanks,
    ramsey

    it's OK guys, took me ages but i got it sorted.

  • Need help: question about itunes update problem

    I started up iTunes yesterday and a window popped up saying there was a new version of iTunes to update, so I did it, and now I can't save equalizer presets! The feature doesn't work at all anymore, and it used to work great. It just goes back to Manual every time, and just won't save anything you put in. This really frustrates me, as it was one of my fave things about iTunes. Can anybody tell me what happened? Can I fix it or go back to my old version without losing my library?
    Cheers

    How do I make sure I don't lose my library? if i uninstall and then re-install an older version (which I have on disc), how do I make sure my library comes with me?

  • Two foundation questions about socket

    1
    when I close socket(this Program is still running),I open this socket again,
    why a exception happened?
    this exception is :java.net.SocketException: socket closed
    2
    when I close socket,
    I write:
    write.close();
    read.close();
    cSocket.close();
    this sequence is right?

    1
    when I close socket(this Program is still running),I
    open this socket again,
    why a exception happened?
    this exception is :java.net.SocketException: socket closedIt's in the documentation
    Socket.close()
    2
    when I close socket,
    I write:
    write.close();
    read.close();
    cSocket.close();
    this sequence is right?Harmless, but not necessary.
    The InputStream and OutputStream objects you get from Socket are just java internal constructs that use the socket filehandle. Not explicitly closing them does not cause a filehandle leak or anything like that. If you are paranoid you can doif (!Csocket.isClosed()) write.flush();
    write = null;
    read = null;
    if (!cSocket.isClosed()) cSocket.close();
    cSocket = null;

  • Simple question about sockets and streams - please answer it!

    Hi
    I have a server socket and a client socket. Both are up and runing. But I'm having problems to send a string from the client and read only the four first bytes on the server. Please read the code and some other comments below:
    socket client:
    DataOutputStream out =
    new DataOutputStream(socket.getOutputStream());
    // read from keyboard input
    BufferedReader myinput =
    new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Type any 4 chars and [enter].");
    String any = myinput.readLine();
    out.writeBytes(any);
    out.flush();
    server socket:
    in = new DataInputStream(socket.getInputStream());
    byte[] id = new byte[4];
    in.read(id, 0, 4);
    System.out.print(new String(id));
    According to the code, it should read 4 bytes from the input stream (in.read(id, 0, 4)), but it displays only the first byte. For example, if I type "hello" on client, the serve should show "hell" but it shows just "h"
    Any ideias? Thanks!

    Hi,
    Check the Javadoc for 'in.read(id, 0, 4);' This reads up to 4 bytes and returns the number of bytes read. You need something along the lines of
    int count = 0;
    while (count < 4)
    count += in.read(id, count, 4-count);
    Roger

  • Help, question about "select ... for update nowait"

    There is a proc code. In the beginning of the code, I used a SQL "select ... for update nowait" in order to prevent from another proc executing at the same time. When the case happens, "-54, ORA-00054: resource busy and acquire with NOWAIT specified" will be printed in the screen.
    But there is a question: I need to print sth to indicate "another proc is running". I used "if (sqlca.sqlcode == -54)" as precondition, such as:
    if (sqlca.sqlcode == -54) {
    printf("There is another proc running.\n");
    However, this line will not be printed. I doubt that the code quits directly when using "select ... for update nowait" so as not to set value (-54) to sqlca.sqlcode.
    So, could you suggest whether there is another way that I can use to print "There is another proc running" when another proc is running?
    Thx a lot for your kindly reply.

    Yes, that link. Scroll down a bit and you will see:
    The calling application gets a PL/SQL exception, which it can process using the error-reporting functions SQLCODE and SQLERRM in an OTHERS handler. Also, it can use the pragma EXCEPTION_INIT to map specific error numbers returned by raise_application_error to exceptions of its own, as the following Pro*C example shows:
    EXEC SQL EXECUTE
    /* Execute embedded PL/SQL block using host
    variables v_emp_id and v_amount, which were
    assigned values in the host environment. */
    DECLARE
    null_salary EXCEPTION;
    /* Map error number returned by raise_application_error
    to user-defined exception. */
    PRAGMA EXCEPTION_INIT(null_salary, -20101);
    BEGIN
    raise_salary(:v_emp_id, :v_amount);
    EXCEPTION
    WHEN null_salary THEN
    INSERT INTO emp_audit VALUES (:v_emp_id, ...);
    END;
    END-EXEC;
    This technique allows the calling application to handle error conditions in specific exception handlers.

  • Sorry quick question about socket apps?

    Does anyone know if there is any sort of device you can use via iphone app to work electrical sockets when you are not home, ie u plug the socket into some sort of adapter like those timer ones but that you can work via your phone? Just thinking if stuck at work etc can put lights on etc, I can't seem to find it so I'm guessing it doesn't exist? Thanks

    Hi,
    If you are searching for an iPhone app, post in the iPhone forum here.
    http://discussions.apple.com/category.jspa?categoryID=201
    Also, launch iTunes. Select iTunes Store on the left then select *App Store* in the menu then select iPhone.
    Try searching there. This is the Mac App Store forum for the Mac OS X.
    Carolyn

  • Few questions about sockets

    I'm trying to make a multiclient/server program. Few problems i stumbled upon.
    1. sending objects, i found that i have to serialize the object and send it.... but it never makes it :-/
    2. is it possible for the client to send/recieve data from the server, by giving the server the data without it requesting it, and by just asking for the data?
    Any tips would help also.

    i get this error when recieving the first time, then i get StremCorrupted exception
    SerializedObject; local class incompatible: stream classdesc serialVersionUID = 8650117693401840898, local class serialVersionUID = 839751141149923839
    Ya, i flushed the output.
    as for number 2...
    I think it was kinda answered, not sure. This server is going to be for a small "game" and i want the clients to send their data to the server, so the server can combine all of the clients data into 1 big array, that i can then send to the client when it is requested.
    I dont want the client to get data from 1 or 2 processes ago, thats why i want it to request for it when its ready, and not get it when its not needed. Because wouldn't that de-sync the clients?
    i hope that makes sense...

  • Help  question about calculating sum????

    what do i need to fix to make it so the digits add together to give a sum i know its in the loop but i cant figure it out can someone giv me a hint
    thanks
    import java.util.Scanner;
    import javax.swing.JOptionPane;
    public class ch10q8
        public static void main(String[] args)
            String input;
            char[] array;
            int digits = 0;
            input = JOptionPane.showInputDialog("Enter numbers seperated by commas");
            array = input.toCharArray();
            for (int i =0; i < array.length; i++)
                if (Character.isDigit(array))
    digits++;
    JOptionPane.showMessageDialog(null, "The digits total" + digits);
    System.exit(0);

    Hey Mr. javakinglow, you never responded to replies in your last three threads:
    [thread 1|http://forums.sun.com/thread.jspa?threadID=5376244&messageID=10656940#10656940]
    [thread 2|http://forums.sun.com/thread.jspa?threadID=5376219&messageID=10656857#10656857]
    [thread 3|http://forums.sun.com/thread.jspa?threadID=5373645&messageID=10642792#10642792]
    This kind of implies that you possibly didn't even read the replies and that you'll likely not read or respond to replies to this thread. Are you sure that this is the message that you want to send?
    Best of luck.

  • I hava a question about RMI,please help me!

    Ladys and Gentleman,I hava a question about RMI.I wirte four little programs in java that is about RMI on my PC.
    import java.rmi.*;
    public interface AddServerIntf extends Remote{
    double add(double d1,double d2) throws RemoteException;
    import java.rmi.*;
    import java.rmi.server.*;
    public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf{
    public AddServerImpl() throws RemoteException{
    public double add(double d1,double d2)throws RemoteException{
    return d1+d2;
    import java.net.*;
    import java.rmi.*;
    public class AddServer{
    public static void main(String args[]){
    try{
    AddServerImpl addServerImpl=new AddServerImpl();
    Naming.rebind("AddServer",addServerImpl);
    }catch(Exception e){
    e.printStackTrace();
    import java.rmi.*;
    public class AddClient
         public static void main(String args[]){
         try{
         String addServerURL="rmi://"+args[0]+"/AddServer";
         AddServerIntf addServerIntf=(AddServerIntf) Naming.lookup(addServerURL);
         System.out.println("The first number is: "+args[1]);
         double d1=Double.valueOf(args[1]).doubleValue();
         System.out.println("The second number is: "+args[2]);
         double d2=Double.valueOf(args[2]).doubleValue();
         System.out.print("The sum is: "+addServerIntf.add(d1,d2));
         }catch(Exception e){
         System.out.println("Exception: "+e);
    And I compiled these files,so I got 4 class files(AddServer.class,AddServerIntf.class,AddServerImpl.class,AddServerClient.class).Then I use "rmic AddServerImpl" got another two files(AddServerImpl_Skel.class and AddServerImpl_Stub.class).Then I input command:rmiregistry,in another window,I input command:java AddServer,I got some exceptions,I was confused by these exceptions.The exception is:
    D:\MyJava\rmi_3>java AddServer
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: AddServerImpl_Stub
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: AddServerImpl_Stub
    java.lang.ClassNotFoundException: AddServerImpl_Stub
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
    at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
    at sun.rmi.server.UnicastRef.invoke(Unknown Source)
    at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
    at java.rmi.Naming.rebind(Unknown Source)
    at AddServer.main(AddServer.java:8)
    But some times this exception will not appeared.Who can give me answer or suggestion,thanks a lot.
    By the way,when I run shutdown.bat in tomcat_root\bin,I can get some exceptions:
    C:\Tomcat\bin>shutdown
    Using CATALINA_BASE: ..
    Using CATALINA_HOME: ..
    Using CATALINA_TMPDIR: ..\temp
    Using JAVA_HOME: C:\JDK
    Catalina.stop: java.net.ConnectException: Connection refused: connect
    java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:350)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:137)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:124)
    at java.net.Socket.<init>(Socket.java:268)
    at java.net.Socket.<init>(Socket.java:95)
    at org.apache.catalina.startup.Catalina.stop(Catalina.java:579)
    at org.apache.catalina.startup.Catalina.execute(Catalina.java:402)
    at org.apache.catalina.startup.Catalina.process(Catalina.java:180)
    at java.lang.reflect.Method.invoke(Native Method)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:203)
    I use Windows server 2000+JDK 1.3.1_04+tomcat 4.1.7

    Maybe I am off base here but it seems to me the problem is the way in which you bind your server. The server must be bound to the same address and you are looking up from, i.e. "rmi://" host "/AddServer"
    so
    Naming.rebind("AddServer",addServerImpl);should be
    Naming.rebind("rmi://127.0.0.1/AddServer", addServerImpl);to match
    String addServerURL="rmi://"+args[0]+"/AddServer";
    AddServerIntf addServerIntf=(AddServerIntf)
    Naming.lookup(addServerURL);Hopefully this will solve your problem, if not it is a problem with your classpath. An easy way to make sure it can see your files is to set the java.rmi.server.codebase to point to where your classes are, e.g.
    java -Djava.rmi.server.codebase=file:"c:\\cygwin\\home\\tweak\\keck_folder\\cmsi401\\RMIGalaxySleuth\\classes\\" AddServer
    I had to set the codebas for my rmi stuff to work no matter how much I messed with the classpath.
    Hope this helps,
    Will

  • Question about the ability of Genius Bar to help with outside software...

    Hi I wasn't sure where to put this, but here's my question. I'm having a problem with the Sims 2 on my Macbook and I was wondering if I go to the Genius Bar will they be able to help me or are they strictly hands off when it's not a direct Apple product?
    Also, I bought an external hard drive in the Apple Store but it's not an Apple branded product. If I'm having a problem with that, can I go to the Apple Store?

    If it's a question about the installation, system requirements or compatibility with your MacBook, the Mac Genius can probably help. If you're having some kind of issue while using the Sims 2, you'll probably have to contact .
    The same is true with the hard drive. If you need some help getting it connected or even formatted, they can probably help. However, if it's not powering up or you're losing files or some kind of operational issue with the hard drive after it's connected, they'll probably refer you to the manufacturer.
    Usually Apple can't support other vendors' products. Someone here may be able to give you some more advice, since none of us work for Apple. There may be someone here who's already had the same issue with the Sims.
    -Doug

  • Please help me about question security because in my apple id no have for restart or chenge my answer

    please help me about answer security question in my apple id because im forgot for my answer, in my apple id no have for change answer, tell me for this please because i love my iphone.
    <Email Edited by Host>

    You need to ask Apple to reset your security questions; this can be done by clicking here and picking a method, or if your country isn't listed, filling out and submitting this form.
    They wouldn't be security questions if they could be bypassed without Apple verifying your identity.
    (110899)

  • Question about 890GXM-GD65 ? any help..? tq

    Dear people..
    I have a question about this board MSI 890GXM-GD65, maybe somebody could help me with the answer...Do the board have an unlock cpu core bios like 785GM-E51 ...? thanx in advance..

    Have a look: http://eu.msi.com/index.php?func=downloaddetail&type=manual&maincat_no=1&prod_no=2012

  • Hello , I want to ask some question about ipads \  How powerful is the iPad?  How useful is it for reading books, newspaper or magazines or for surfing the web? Can you identify any shortcomings of the device?   please help me :(

    Hello ,
    I want to ask some question about ipads \
    How powerful is the iPad? 
    How useful is it for reading books, newspaper or magazines or for surfing the web?
    Can you identify any shortcomings of the device?  
    please help me

    it's less powerful than your average computer. THink of it like a netbook but with a better processor.
    It'll do fine for surfing (although if you browse a lot of flash based sites you will need to get a third party browser since safari doesn't accommodate it)
    You may do OK on reading books, papers or magazines, especially if they have apps, but the ipad's screen is backlit, so it doesn't work well outdoors and you may need to fiddle with the brightness so that you don't get eye strain (it's just like doing too much reading from a computer screen)
    I would say the biggest short comings are data transfer. Apple's preferred work flow is that everything is done via iTunes or the internet....well people dont' always have 100% reliable always on internet access so you can find yourself in a situation where you can't get things on/off the iPad.
    By and large, it's a good device for day to day stuff, but is not a computer replacement.

Maybe you are looking for