Using Sockets to connect comps

I have two computers that I am trying to connect with each other.
I used the code at the site:
http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets-p2.html
At the bottom of the page there is the code for the server and the client.
First I changed "hostname" to my server's IP address.
Then I ran the server on one computer and then ran the client on the other.
After i ran the client, it gave me an IO exception
What did I do wrong?
thanks in advance

I am certain that the server was running.
How do i pick what port number to use. I just chose randomly 1200
On the server side I used 123
Do the port numbers have to match? Is there a way to find out what port is a good one to use?

Similar Messages

  • When client use socket to connect server, server how to get client IP

    as topic

    Your ServerSocket has an accept() method that gives you a Socket. The Socket class has a getInetAddress() method... I'll let you continue reading the API documentation from here.

  • Can i use the same socket to connect to more than one servers

    hi,
    I'm new to java. I want to know whether a socket created using Socket() constructor can be used to connect to multiple servers, not necessarily at a particular point of time. ie, i want to connect to various servers using a single socket and register some info abt them, possible using a loop, one by one. I use connect() method to connect to particular server.
    In other words is Socket class is mutable.
    Edited by: itsraja on Feb 25, 2008 5:50 AM

    In short, I don't think so.
    Setting the server name for a socket is in the constructor.
    Socket s = new Socket("localhost", 501);I don't believe that there are any functions, such as:
    s.setHost("localhost");
    s.setPort(501);However, JavaDocs suggests that when you use the no-args constructor, your class becomes an automatic SocketImpl class, but you can't reach any of its variables unless you derive from the class, itself. But that's probably a bigger headache than it's worth.
    Now TECHNICALY, if you didn't want to create a new variable, you could use:
    Socket s = new Socket("localhost", 501);
    s.close();
    s = new Socket("remotehost", 502);
    s.close();However, this is still creating a new instance and thus a new object in memory.
    I hope this answers your question.
    Let us know exactly what you're trying to do for a more exact answer.
    ~Derek

  • How to make a peer to peer connection in a network using sockets

    My Project is about a multi agent meeting scheduling system.. I've kept the DB in the server and I only use the server to retrieve data from the database. I have used sockets to communicate with the server.
    Each peer in the network is an agent for a perticular user and these agents will be communicating with each other for negotiation purposes..
    The problem I have is that, I couldnt communicate wit other peers using sockets.. I couldnt find any sample java code of sockets to overcum this problem.f sumone has a sample code plz send me.
    And if there is a more efficient and easy way I can connect these peers except sockets, plz tell me and if u have a sample java code plz be kind enough to send.
    This is my final year project in the University
    Thank you
    Sajini De Silva ([email protected])

    Hi Sajinidesilva,
    I think you'll find more support in the [JXTA Community|https://jxta.dev.java.net/] for your project. Also, there's an interesting article to start with : [Introduction to the Peer-to-Peer Sockets Project|http://www.onjava.com/pub/a/onjava/2003/12/03/p2psockets.html].

  • Connect applet to server port using sockets? Please help!!!

    I am trying to connect a java applet to game1.pogo.com:5285 which is their gaming port. I want to make it connect from my website which is ucichess.com
    The applet can be found here: http://ucichess.com/index.html and the java console gives me a bunch of weird errors if u can take a look at it:
    network: Disconnect connection to http://ucichess.com/applet/chess2/com/pogo/util/thin/e.class
    network: Cache entry found [url: http://ucichess.com/applet/chess2/com/pogo/util/thin/m.class, version: null]
    network: Connecting http://ucichess.com/applet/chess2/com/pogo/util/thin/m.class with proxy=DIRECT
    network: ResponseCode for http://ucichess.com/applet/chess2/com/pogo/util/thin/m.class : 304
    network: Encoding for http://ucichess.com/applet/chess2/com/pogo/util/thin/m.class : null
    network: Disconnect connection to http://ucichess.com/applet/chess2/com/pogo/util/thin/m.class
    network: Connecting socket://ucichess.com:5285 with proxy=DIRECT
    Sun Jul 22 17:14:24 EDT 2007     Thread-198          ArenaServiceThin.error
    Sun Jul 22 17:14:24 EDT 2007     Thread-198          exception
    java.net.ConnectException: Connection refused: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.SocksSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.<init>(Unknown Source)
         at java.net.Socket.<init>(Unknown Source)
         at com.pogo.besl.thin.c.<init>(SourceFile)
         at com.pogo.besl.thin.a.<init>(SourceFile)
         at com.pogo.besl.arena.a.g(SourceFile)
         at com.pogo.besl.arena.a.a(SourceFile)
         at com.pogo.game.arena.chat.ChatArenaApplet.a(SourceFile)
         at com.pogo.game.arena.chat.ChatArenaApplet.b(SourceFile)
         at com.pogo.client.ping.b.run(SourceFile)
    network: Connecting http://ucichess.com/blank.html?confuser=-6956021725811422401 with proxy=DIRECT
    Applet.terminate(false, false)
    ChatArenaApplet.disposeLocals(false)
    InvalQueue thread exiting: InvalQueue-1-com.pogo.ui.a[panel8,0,0,458x403,invalid]
    ChatArenaApplet.disconnect()
    Applet.disposeLocals(false) - ChessTable
    network: Cache entry not found [url: http://ucichess.com/applet/chess2/META-INF/assets.txt, version: null]
    network: Connecting http://ucichess.com/applet/chess2/META-INF/assets.txt with proxy=DIRECT
    basic: Stopping applet ...
    basic: Removed progress listener: sun.plugin.util.GrayBoxPainter@106433d
    basic: Finding information ...
    basic: Releasing classloader: sun.plugin.ClassLoaderInfo@35dc95, refcount=0
    basic: Caching classloader: sun.plugin.ClassLoaderInfo@35dc95
    basic: Current classloader cache size: 2
    basic: Done ...
    basic: Joining applet thread ...
    basic: Destroying applet ...
    basic: Disposing applet ...
    basic: Quiting applet ...
    ChatArenaApplet.disposeGlobals()
    Timer thread exiting: ScrollbarButtonRepeater
    network: Cache entry found [url: http://ucichess.com/applet/chess2/com/pogo/ui/b.class, version: null]
    basic: Joined applet thread ...
    network: Connecting http://ucichess.com/applet/chess2/com/pogo/ui/b.class with proxy=DIRECT
    network: ResponseCode for http://ucichess.com/applet/chess2/com/pogo/ui/b.class : 304
    network: Encoding for http://ucichess.com/applet/chess2/com/pogo/ui/b.class : null
    network: Disconnect connection to http://ucichess.com/applet/chess2/com/pogo/ui/b.class
    network: Cache entry found [url: http://ucichess.com/applet/chess2/com/pogo/ui/q.class, version: null]
    network: Connecting http://ucichess.com/applet/chess2/com/pogo/ui/q.class with proxy=DIRECT
    network: ResponseCode for http://ucichess.com/applet/chess2/com/pogo/ui/q.class : 304
    network: Encoding for http://ucichess.com/applet/chess2/com/pogo/ui/q.class : null
    network: Disconnect connection to http://ucichess.com/applet/chess2/com/pogo/ui/q.class
    Applet.disposeGlobals - ChessTable
    Applet.terminate completed
    Is it possible for me to host the applet on my server and connect it to a remote server using sockets and verification or is that against java security?
    Applet.stop - ChessTable
    Applet.stop completed - ChessTable
    Applet.destroy - ChessTable
    Applet.destroy completed - ChessTable
    ChatArenaApplet.disconnect()

    Hi yoshistr, have you resolved your issue? If you have, do you mind sharing it with me?
    Thanks.

  • Nokia 2730 does not allow to use socket connection

    I recently bought a Nokia 2730 Classic, but I am not able to browse internet on this phone through the Socket connection, like how the other Nokia 2330 Classic can do.
    For the Nokia 2330 Classic, I need just put the SIM into it and start the phone, then go to the configuration and just select Internet APN as the Access Point and the phone will work fine with Opera Mini and other Java applications like Ebuddy, Bolt Browser etc through “socket” connection”, without the need to request the internet settings from my operator through SMS.
    But in the Nokia 2730 Classic when I put the same SIM into this phone and Select the same Internet APN as the Access point, I am not able to browse the internet on Opera Mini and I have to send SMS to my operator to get the settings.
    The main problem here is that even after saving the internet Settings of my operator on the Nokia 2730 Classic, the internet does not work on in the Socket Connection, hence Opera Mini 4.2 and 5.1 (and other java applications which need the socket connection) will not install or work. (although the internet will work on the default browser of the phone)
    I am also able to connect the Nokia 2730 Classic to the computer and browse the internet through Data Cable / Bluetooth normally.
    I tried with another operator using an internet data plan, but got the same results.
    Can someone please tell me how to adjust the settings correctly so that the Nokia 2730 will work on the Socket connection so that I can browse on Opera Mini 5.1 and 4.2 and other Java browsers and applications which work only on the Socket connection?
    Another strange issue is that after trying to use the internet on the Nokia 2730 (without any positive results), when I put the same SIM back into the Nokia 2330, the internet does not work for some hours on the socket connection and I have to use the http connection till then. Quite strange.
    Any help will be greatly appreciated.

    My problem is sounds to be somehow related to this. Actually, I do not have reference if the problem was already on SW version 9.41 (?), but at least after the firmware upgrade (v 10.40) I get the following message "Suojattu yhteys ei käytettävissä" ~ in English "Secure connection not available" when trying to open https links e.g. directly from text message.
    Obviously, the same problem happens with I try to download an application from Ovi. I am able to browse the applications in the service, but once trying to download/install the problem occurs.
    Opera is capable to open the https connection, but OVI does not support it => there is no way to install any application from Ovi. I have tried both Elisa and Saunalahti SIMs, but it seems not to be a settings releated.
    One note still in the firmware upgade: when doing it it first time, there was an error when restoring the backup. I made the firmware upgrade couple of times again and even so that I did not restore the backup.
    Could it be that the first time firmware upgrade somehow bricked the phone? I have also been wondering, why there is no settings menu available in Web section?
    Any ideas?
    BR,
    Mika
    /* Mika */

  • Applet using socket connection always go through proxy server

    Socket connection with socks always go through proxy server
    We have two applets in different codebases using socket to talk to each other, until now nothing new, but the problem is that we are behind a proxy server with socks and because of that, the connection always go through the proxy server even with proxy override point to the applet machine. We have tried a lof of things and until now nothing worked, it looks like the socket is ignoring proxy override configuration. We would like to know if there is a way to solve this problem making the applets comunicate to each other ignoring the proxy server. It should happen when we set the plug-in option to "no proxy host", but it doesn't. Maybe it can be a bug of JVM, I don't know, just maybe, and if it's true, any other good idea would be welcome as well.
    Thanks in advance.

    Hi,
    I am not very much sure if I can help you. In my previous experience, once you set the system property to use the proxy, then the jvm uses the proxy. If you want disable, in your code, you have to disable it.
    like System.setProperty("socksProxyHost","someHost"), Properties props = System.getProperties(); props.remove(("socksProxyHost");

  • Using Sockets TCP/IP to connect through Proxies and Firewalls

    How to do in a Client/server Application using Sockets TCP/IP to connect through Proxies and Firewalls?
    How to implement the HTTP Tunnelling in this case?
    the code in Client to connect to server is:
    SSLSocketFactory sslFact = (SSLSocketFactory)SSLSocketFactory.getDefault();
                   socket = (SSLSocket)sslFact.createSocket(c.site, c.PORT);
              String [] enabledCipher = socket.getSupportedCipherSuites ();     
                   socket.setEnabledCipherSuites (enabledCipher);
                   out = new ObjectOutputStream(socket.getOutputStream());
                   in = new ObjectInputStream(socket.getInputStream());
    The Server is an executable Standalone Application with a main Function � How to do to convert this Server in a Servlet Application?
    the code in Server to wait client connections is:
    Runtime.getRuntime().addShutdownHook(new ShutdownThread(this));
              try {
                   SSLServerSocketFactory factory = (ServerSocketFactory) SSLServerSocketFactory.getDefault();
                   SSLServerSocket sslIncoming =
                        (SSLServerSocket) factory.createServerSocket (PORT);
                   String [] enabledCipher = sslIncoming.getSupportedCipherSuites ();
                   sslIncoming.setEnabledCipherSuites (enabledCipher);
              while(running) {
                        SSLSocket s = (SSLSocket)sslIncoming.accept();
                   newUser(s, pauseSyn);
              } catch (IOException e) { System.out.println("Error: " + e); }
    some links or code sample?
    Thanks in Advance

    Did you see this: Networking Properties?
    Including
    SOCKS protocol support settings
    and
    http.proxyHost (default: <none>)
    http.proxyPort (default: 80 if http.proxyHost specified)
    http.nonProxyHosts (default: <none>
    ftp.proxyHost (default: <none>)
    ftp.proxyPort (default: 80 if ftp.proxyHost specified)
    ftp.nonProxyHosts (default: <none>)

  • OSB using socket Transport ,how to keep a TCP connection open

    hi my firends,
    i met a problem , our project need build an OSB to control a socket service which is able to transfer a big data file (maybe a voice file,*.wav),and the client program will play the voice file on live.
    So my solution is that : keep a socket (tcp) connection open,client listen port and makes date play.
    but i can't make the OSB socket transport alway open,it will timeout after a few second if have none date received.
    how could i deal with it ... pls let me konw if you have any idea...i will wait you on line
    thanks guys

    Hi,
    I'm not sure if that's achievable using OSB, and even if it was, I don't think OSB was designed having this type of application in mind...
    I understand that you need a media streaming solution and I'm pretty sure that there are plenty of tools out there that can help you in doing that, and maybe some of them can be integrated with OSB in some way...
    Cheers,
    Vlad

  • A GUI problem when using sockets

    I have a problem with Client.java. it creates a socket to connect to a serversocket. I do this through the method "runClient()" .
    the problem is that if I call runClient from an actionlistener add to a button. here the graphics of the window will disappear and you will be stuck for reading input (input.readObject())
    On the other hand , if you call runClient automatically from the class constructor "Client()" the program will work normally.
    can anybody give me a hint what's going on?
    Why does the program blocks in the first case for input?why not the second?
    //Client.java
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Client extends JFrame
         private JTextField enter;
         private JTextArea display;
         private JButton connect;
         ObjectOutputStream output;
         ObjectInputStream input;
         String message = "";
         public Client()
              super("Client");
              Container c = getContentPane();
              enter = new JTextField();
              enter.setEnabled(false);
              enter.addActionListener(
                   new ActionListener() {
                                  public void actionPerformed(ActionEvent e)
                                       sendData(e.getActionCommand());
              c.add(enter ,BorderLayout.NORTH);
              display = new JTextArea();
              c.add(new JScrollPane(display), BorderLayout.CENTER);
              connect = new JButton("Connect");
              connect.addActionListener(
                   new ActionListener() {
                                  public void actionPerformed(ActionEvent e)
                                       //TRY THIS . . it won't work
                                       //runclient();     
              c.add(connect, BorderLayout.EAST);
              setSize(400,300);
              show();
              //This works normally
              runClient();
         public void runClient()
              Socket client;
              try
                   display.setText("attempting to connect \n");
                   client = new Socket(InetAddress.getByName("127.0.0.1"),3500);
                   display.append("connected to : " + client.getInetAddress().getHostName());
                   output = new ObjectOutputStream(client.getOutputStream());
                   output.flush();
                   input = new ObjectInputStream(client.getInputStream());
                   display.append("\nGot I/O streams\n");
                   String message = "Client>>> Connection successful";
                   output.writeObject(message);
                   output.flush();
                   enter.setEnabled(true);
                   //YOU WILL GET STUCK HERE
                   do
                        try
                             message = (String) input.readObject();
                             display.append("\n" + message);
                             display.setCaretPosition(display.getText().length());
                        catch(ClassNotFoundException cnf)
                             display.append("unknown error\n");
                   } while( !message.equals("SERVER>>> TERMINATE"));/**/     
                   display.append("\nClosing Connection");
                   input.close();     
                   output.close();
                   client.close();
              catch(EOFException eof)
                   System.out.println("Server terminated connection");
              catch(IOException io)
                   JOptionPane.showMessageDialog(this,io.getMessage(),"Server Error",JOptionPane.ERROR_MESSAGE);
         private void sendData(String s)
              try
                   message = s;
                   output.writeObject("CLIENT>>> " + s);
                   output.flush();
                   display.append("\nCLIENT>>>" + s);
                   enter.setText("");
              catch(IOException e)
                   display.append("\nERROR writing object");
    }

    The problem is that you can NOT access a method between classes unless the method is static.
    THIS IS WRONG!
    public class Jack{
    private pale;
    private void GoUpHill()
    {pale = full;}
       public class Jill{
          public init()
          Jack.GoUpHill();
    }It is wrong because "private void GoUpHill()" is not declared as static.
    THIS IS CORRECT!
    public class Jack{
    private pale;
    private void GoUpHill()
    {pale = full;}
       public class Jill{
          public init()
          Jack.GoUpHill();
    }Note that "private static void GoUpHill()" is declared as static. That will work, but it will give an error because "pale" is not declared static. Obviously, you're going to need to make all your objects static... or, you could do this:
    public class Jack{
    private pale;
    private void GoUpHill()
    {pale = full;}
       public class Jill{
          public init()
          Jack jr = new Jack();
          jr.GoUpHill();
    }A new instance of the Jack class is made so you can use GoUpHill() at will. You don't need any static methods or objects if you use that method... but it might not always do what you want it do.

  • Sending file using sockets (difficult)

    Hi, i have the following section of code
    (of which i am not claiming ownership) which
    implements a DCC Send command from irc.
    It accomplishes this using sockets, and while
    i understand how the code accomplishes what it
    does, i need help with a possible modification.
    Basically what i am looking to do is keep track
    of the progress of the send - so that the
    user can at any time see how much of the file
    has been sent and how much is remaining.
    If anyone has done such a thing in the past or
    has a good idea as to how this should be implemented,
    i would be greatful for their help.
    Here is the code:
    new Thread() {
                public void run() {
                    try {
                        ServerSocket ss = new ServerSocket(0);
                        ss.setSoTimeout(timeout);
                        int port = ss.getLocalPort();
                        //byte[] ip = ss.getInetAddress().getAddress();
                        byte[] ip = InetAddress.getLocalHost().getAddress();
                        long ipNum = 0;
                        long multiplier = 1;
                        for (int i = 3; i >= 0; i--) {
                            int byteVal = (ip[i] + 256) % 256;
                            ipNum += byteVal*multiplier;
                            multiplier *= 256;
                        // Rename the filename so it has no whitespace in it when we send it.
                        // .... I really should do this a bit more nicely at some point ....
                        String safeFilename = file.getName().replace(' ', '_');
                        safeFilename = safeFilename.replace('\t', '_');
                        // Send the message to the user, telling them where to connect to in order to get the file.
                        sendCTCPCommand(nick, "DCC SEND " + safeFilename + " " + ipNum + " " + port + " " + file.length());
                        // The client may now connect to us and download the file.
                        Socket socket = ss.accept();
                        socket.setSoTimeout(30000);
                        // Might as well close the server socket now; it's finished with.
                        ss.close();
                        BufferedOutputStream output = new BufferedOutputStream(socket.getOutputStream());
                        BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
                        BufferedInputStream finput = new BufferedInputStream(new FileInputStream(file));
                        byte[] outBuffer = new byte[bufferSize];
                        byte[] inBuffer = new byte[4];
                        int bytesRead = 0;
                        while ((bytesRead = finput.read(outBuffer, 0, outBuffer.length)) != -1) {
                            output.write(outBuffer, 0, bytesRead);
                            output.flush();
                            input.read(inBuffer, 0, inBuffer.length);
                        output.close();
                        input.close();
                        log("+++ DCC SEND Completed to " + nick + " (" + file.getPath() + ")");
                    }

    You already have the necessary code to find the number of bytes sent at any point during the transmission. You can find out the size of the file by instantiating a RandomAccessFile before you send it, and querying for the file length.
    I suggest you make the file size and bytes sent volatile and conveniently accessible to another thread (best implemented here as an inner class?). Your new thread will need to monitor the file transfer at intervals to update the progress indicator. You can generate estimates of time remaining by measuring the average transmission rate, and extrapolating using the total file size. Classically this is done using an average, but you might be better just maintaining a list of fairly recent samples, allowing for the speed swings inherent in internet connections.
    How you update the progress indicator from your monitor thread is up to you. I suggest exposing methods in the UI for setting the progress and time remaining, and simply update them from the monitor.
    Does this help any?

  • Send html page (with images) using sockets

    I am trying to implement http and am coding this using sockets. So it is a simple client-server set up where the browser queries my server for a webpage and it should be shown. The html itself is fine, but I can't get any of the images to show up! All of my messages give me a status "200 OK" for the images, so I cant understand what my problem is!
    Also, is the status and header lines supposed to be shown in the browser? I didnt think so but it keeps showing up when I query a webpage.
    Please help!
    import java.io.* ;
    import java.net.* ;
    import java.util.* ;
    public final class WebServer
         public static void main(String argv[]) throws Exception
              // Set the port number.
              int port = 8888;
              // Establish the listen socket.
              ServerSocket ssocket = new ServerSocket(port);
              // Establish client socket
              Socket csocket = null;
              // Process HTTP service requests in an infinite loop.
              while (true)
                   // Listen for a TCP connection request.
                   // (note: this blocks until connection is made)
                   csocket = ssocket.accept();     
                   // Construct an object to process the HTTP request message.
                   HttpRequest request = new HttpRequest(csocket);
                   // Create a new thread to process the request.
                   Thread thread = new Thread(request);
                   // Start the thread.
                   thread.start();
    final class HttpRequest implements Runnable
         final static String CRLF = "\r\n";
         Socket socket;
         // Constructor
         public HttpRequest(Socket socket) throws Exception
              this.socket = socket;
         // Implement the run() method of the Runnable interface.
         public void run()
              try
                   processRequest();
              catch (Exception e)
                   System.out.println(e);
         private static void sendBytes(FileInputStream fis, OutputStream os)
         throws Exception
            // Construct a 1K buffer to hold bytes on their way to the socket.
            byte[] buffer = new byte[1024];
            int bytes = 0;
           // Copy requested file into the socket's output stream.
           while((bytes = fis.read(buffer)) != -1 ) {
              os.write(buffer, 0, bytes);
              os.flush();
         private static String contentType(String fileName)
              fileName = fileName.toLowerCase();
              if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
                   return "text/html";
              if(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") ) {
                   return "image/jpeg";
              if(fileName.endsWith(".gif")) {
                   return "image/gif";
              return "application/octet-stream";
         private void processRequest() throws Exception
              // Get a reference to the socket's input and output streams.
              InputStream is = socket.getInputStream();
              DataOutputStream os = new DataOutputStream(socket.getOutputStream());
              // Set up input stream filters.
              InputStreamReader ir = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(ir);
              // Get the request line of the HTTP request message.
              String requestLine = br.readLine();
              // Display the request line.
              System.out.println();
              System.out.println(requestLine);
              // Get and display the header lines.
              String headerLine = null;
              while ((headerLine = br.readLine()).length() != 0)
                   System.out.println(headerLine);
              // Extract the filename from the request line.
              StringTokenizer tokens = new StringTokenizer(requestLine);
              tokens.nextToken();  // skip over the method, which should be "GET"
              String fileName = tokens.nextToken();
              // Prepend a "." so that file request is within the current directory.
              fileName = "C:\\CSM\\Networking\\Project1" + fileName;
              // Open the requested file.
              FileInputStream fis = null;
              boolean fileExists = true;
              try {
                   fis = new FileInputStream(fileName);
              } catch (FileNotFoundException e) {
              fileExists = false;
              // Construct the response message.
              String statusLine = null;
              String contentTypeLine = null;
              String entityBody = null;
              if (fileExists) {
              statusLine = "200 OK" + CRLF;
              contentTypeLine = "Content-type: " +
                   contentType( fileName ) + CRLF
                   + "Content-length: " + fis.available() + CRLF;
              else {
              statusLine = "404 Not Found" + CRLF;
              contentTypeLine = "Content-type: text/html" + CRLF;
              entityBody = "<HTML>" +
                   "<HEAD><TITLE>Not Found</TITLE></HEAD>" +
                   "<BODY>Not Found</BODY></HTML>";
              // Send the status line.
              os.writeBytes(statusLine);
              System.out.println(statusLine);
              // Send the content type line.
              os.writeBytes(contentTypeLine);
              System.out.println(contentTypeLine);
              // Send a blank line to indicate the end of the header lines.
              os.writeBytes(CRLF);
              // Send the entity body.
              if (fileExists)     
                   sendBytes(fis, os);
                   fis.close();
              // file does not exist
                     else
                   os.writeBytes(entityBody);
              // Close streams and socket.
              os.flush();
              os.close();
              br.close();
              socket.close();
    }

    ok. i figured it out. STUPID mistake. i forgot to include "HTTP/1.1" in my status line!!!

  • Downloading a binary file using sockets without length known

    Hi all,
    I'm trying to download a binary(.exe) file using socket, where the length of the file is not known. Please take a look at the code I'm using:
          var readBin = socketBin.read();
         <-- Here comes the code that checks for http Content-length header field
         ; If content-length field is available, then I'll use it to download file, else proceed with following code -->
        pBar.reset("Downloading plugin..",null);pBar.hit(readBin.length);       
                while (1)
                    binFil.write(readBin);     //'binFil' is the file, into which downloaded file is written.
                    readBin = socketBin.read();
                    pBar.hit(readBin.length);
                    if( socketBin.eof || readBin.length<=0){
                        break;}          
                binFil.write(readBin);
                binFil.close();
                socketBin.close();
    Problem is: I'm able to download file within 10 seconds when content-length is known. But when content-length is not known, its taking about 1 and half minute to download, also the progress bar gets struck for much of time.
    FYI: socket is opened in binary mode, file is getting downloaded correctly(even though it takes abt a minute). BTW Im using CS5.5 extendscript
    I'm not able to figure out where the bug is.

    Hi, Srikanth:
    Sevaral points.
    #1 When posting code, please use the web interface and the >> icon and choose Syntax Highlighting >> Java. Otherwise your code is just too hard to read and gets misformatted.
    #2 Apropos of #1, your script as written does not work, because this line:
    url=url.replace(/([a-z]*):\/\/([-\._a-z0-9A-Z]*)(:[0-9]*)?\/?(.*)/,"$ 1/$2/$3/$4");
    has an extra space in the $1 and should be this:
    url=url.replace(/([a-z]*):\/\/([-\._a-z0-9A-Z]*)(:[0-9]*)?\/?(.*)/,"$1/$2/$3/$4");
    Please take an extra moment to make sure that when you asking for help, you do so in a way that makes sense. Otherwise it takes too much effort to help you, and that is frustrating.
    #3 If we instrument your script by adding a line to the while() loop:
                while (1)
                    binFil.write(readBin);
                    readBin = socketBin.read();
                    $.writeln(Date()+" Read "+readBin.length+" chars, eof is "+socketBin.eof);
                    if(  readBin.length<=0){         break;}              
    We get output like this:
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:06:56 GMT-0400 Read 631 chars, eof is false
    Mon Jul 11 2011 12:07:06 GMT-0400 Read 0 chars, eof is false
    Result: undefined
    Therefore, we can reasonably conclude that the last read at the end of the data stream returns a short read when the other side blocks.
    Unfortunately, that's clearly insufficient since you can get short reads all the time.
    I'm not sure why you say the length of the file is not known, HTTP provides it to you in the Content-Length field of the response.
    But the easy answer is to get the server to close it for you. This is easy, enough, with Connection: close. Why were you specifying
    Connection: keep-alive, anyhow?:
                var requestBin =
                "GET /" + parsedURLBin.path + " HTTP/1.1\n" +
                "Host: " + parsedURLBin.address + "\n" +
                "User-Agent: InDesign ExtendScript\n" +
                "Accept: */*\n" +
                //"Connection: keep-alive\n\n";
                "Connection: close\n"+
                "\n";
    This yields a nice tidy:
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 1024 chars, eof is false
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 735 chars, eof is true
    Mon Jul 11 2011 12:26:19 GMT-0400 Read 0 chars, eof is true
    I suspect you're also better off using something like socketBin.read(64*1024) for a 64k buffer size, but it doesn't seem to effect the on-the-wire protocol, so perhaps its not so important.
    If you don't want to reply on the server

  • Networking Using Socket

    Hi,
    My team have developed a real-time remote network monitoring system. It consists of server and agent. What the agent does is send the network traffic data to server every one second by using socket. Each second we send the data to the same socket and yes we already make sure that the socket and streams used are closed after data being sent. However I still see a lot of SocketException once in a while whenever the agent tries to send the data.
    1. How can I solve this error ?
    2. Is it possible that I connect to my server just once without closing the connection and still able to send the data every second ?
    Thank you for your time.
    Regards,
    Mustafa
    Below is the code, called every one second :
          * This method sends itself into the server using compressed input/output
          * stream and then will receive back the instance of "replied" CRequest and
          * then further returns it.
          * @return CRequest
         public CRequest sendRequest() {
              SSLSocket server = null;
              GZIPOutputStream gos = null;
              ObjectOutputStream out = null;
              BufferedOutputStream bos = null;
              GZIPInputStream gis = null;
              ObjectInputStream in = null;
              try {
                   SSLSocketFactory sslFact = (SSLSocketFactory) SSLSocketFactory
                             .getDefault();
                   server = (SSLSocket) sslFact.createSocket(hostname, port);
                   String set[] = new String[] { "SSL_RSA_WITH_NULL_MD5" };
                   server.setEnabledCipherSuites(set);
                   server.setReceiveBufferSize(48000);
                   server.setSendBufferSize(48000);
                   if (milisecTimeout != 0) {
                        server.setSoTimeout(milisecTimeout);
                   gos = new GZIPOutputStream(server.getOutputStream());
                   bos = new BufferedOutputStream(gos, 48000);
                   out = new ObjectOutputStream(bos);
                   // /* Can we actually send ourselves and then receive ourselves?*/
                   out.writeObject(this);
                   out.flush();
                   bos.flush();
                   gos.finish();
                   gis = new GZIPInputStream(server.getInputStream());
                   in = new ObjectInputStream(new BufferedInputStream(gis, 48000));
                   /* Returning the newly modified request with results */
                   return (CRequest) in.readObject();
              } catch (Exception e) {
                   System.out.println("trouble sending request" + e);
              } finally {
                   if (gos != null) {
                        try {
                             gos.close();
                             // System.out.println("GOS closed..");
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        gos = null;
                   if (out != null) {
                        try {
                             out.close();
                             // System.out.println("OUT closed..");
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        out = null;
                   if (gis != null) {
                        try {
                             gis.close();
                             // System.out.println("GIS closed..");
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        gis = null;
                   if (in != null) {
                        try {
                             in.close();
                             // System.out.println("IN closed..");
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        in = null;
                   if (server != null) {
                        try {
                             server.close();
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        server = null;
                   System.gc();
              return null;
         }

    I've been trying to modify my sendRequest function, so that It will only open and close the connection ONCE. As long as the connection is open I need to be able to send some data to the server. However I've been getting errors and stuffs like that.
    Exception:
    java.io.NotSerializableException: java.io.BufferedOutputStream
    +     at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1081)+
    +     at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1375)+
    +     at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1347)+
    +     at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1290)+
    +     at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1079)+
    +     at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:302)+
    +     at com.inetmon.jn.commobj.CRequest.sendRealTimeRequest(CRequest.java:385)+
    +     at com.inetmon.jn.core.internal.CaptureEngine.sendDataBackToServer(CaptureEngine.java:1420)+
    +     at com.inetmon.jn.core.internal.CaptureEngine$4.actionPerformed(CaptureEngine.java:2384)+
    +     at javax.swing.Timer.fireActionPerformed(Timer.java:271)+
    +     at javax.swing.Timer$DoPostEvent.run(Timer.java:201)+
    +     at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)+
    +     at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)+
    +     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)+
    +     at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)+
    +     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)+
    received is null
    +     at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)+
    +     at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)+
    The constructor which only be called once.
    public CRequest(Cookie cookie, int id, Object information, String hostname,
                   int port) {
              this.cookie = cookie;
              this.type = RequestConstants.AGENT_SEND_REALTIME_DATA;
              this.id = id;
              this.information = information;
              this.hostname = hostname;
              this.port = port;
              try {
                   SSLSocketFactory sslFact = (SSLSocketFactory) SSLSocketFactory
                             .getDefault();
                   server = (SSLSocket) sslFact.createSocket(hostname, port);
                   String set[] = new String[] { "SSL_RSA_WITH_NULL_MD5" };
                   server.setEnabledCipherSuites(set);
                   server.setReceiveBufferSize(48000);
                   server.setSendBufferSize(48000);
                   if (milisecTimeout != 0) {
                        server.setSoTimeout(milisecTimeout);
                   gos = new GZIPOutputStream(server.getOutputStream());
                   bos = new BufferedOutputStream(gos, 48000);
                   out = new ObjectOutputStream(bos);
              } catch (Exception e) {
                   System.out.println("trouble creating socket" + e);
         }The send request, which sends data whenever I want.
         public CRequest sendRealTimeRequest() {
              try {
                   // gos = new GZIPOutputStream(server.getOutputStream());
                   // bos = new BufferedOutputStream(gos, 48000);
                   // out = new ObjectOutputStream(bos);
                   // /* Can we actually send ourselves and then receive ourselves?*/
                   out.writeObject(this);
                   // out.flush();
                   // bos.flush();
                   // gos.finish();
                   gis = new GZIPInputStream(server.getInputStream());
                   in = new ObjectInputStream(new BufferedInputStream(gis, 48000));
                   /* Returning the newly modified request with results */
                   System.out.println("managed to send once");
                   return (CRequest) in.readObject();
              } catch (Exception e) {
                   e.printStackTrace();
              return null;
         }

  • Send a picture file using sockets

    Hi,
    Could someone please tell me how I can send a picture file using sockets across a TCP/IP network? I have managed to do it by converting the file into a byte array and then sending it but I dont see the data back at the client when I recieve the file. I just see the byte array as having size 0 at client.
    Byte array size is correct at client side.
    //client code
    System.out.println("Authenticating client");
              localServer = InetAddress.getLocalHost();
              AuthConnection = new Socket(localServer,8189);
              out = new PrintWriter(AuthConnection.getOutputStream());
              InputStream is = AuthConnection.getInputStream();
              System.out.println(is.available());
              byte[] store = new byte[is.available()];
              is.read(store);
         ImageIcon image = new ImageIcon(store);
              JLabel background = new JLabel(image);
              background.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
              getLayeredPane().add(background, new Integer(Integer.MIN_VALUE));
    //extra code here
              catch (UnknownHostException e) {
    System.err.println("Don't know about host: LocalHost");
    System.exit(1);
              catch (IOException e) {
    System.err.println("Couldn't get I/O for "
    + "the connection to: LocalHost");
    System.exit(1);
    //server code
                   DataOutputStream out = new DataOutputStream(incoming.getOutputStream());
                   FileInputStream fin = new FileInputStream("3trees.gif");
                   byte[] b = new byte[fin.available()];
                   int ret = fin.read(b);
                   out.write(b);

    i used OutputStream as
    OutputStream out = incoming.getOutputStream(); and flushed the stream too.
    But I still get the same output on the client side. I tried sending a string and it works , but I cant seem to be able to populate the byte array on the client side. It keeps showing zero. Please advise.
    Thank you.

Maybe you are looking for

  • SAP Web Services Call with MQSeries

    Hi all,   Our system is ECC 6.0 NW 7.0 SP15 with no PI and XI. Currently we can connect between SAP and Third party using web services call directly. However, our network & infrastructure team want to use MQseries as a message queue and broker.   We

  • HT4993 i want 2 deleat every thing on my phone how do i do this??

    I want 2 deleat everything on my Iphone and use my previous back up and instal that i just dont know how 2 do that please help

  • Sync photos from iphone5 to iphone5

    I am trying to move photos from my old ihphone5 to my new iphone 5 and it is not importing all albums.

  • Fullscreen slideshow widget

    Does anyone out there know how a close button can be added to the full screen slideshow? The close button is available with a fullscreen slideshow in the lightbox mode but is not available when the lightbox check box is unchecked

  • Failover active/standby

    Hello. There are two Cisco devices: asa5512 and asa5510. Tell me whether it is possible to organize a failover active / standby using these devices. If this is not possible, tell me if there are any other possibilities for automatic backup.