Using sockets...

I'm trying to write a fairly simple client and server. I want them both to not try to connect until a "Connect" button is pressed in their respective GUIs. The idea is that this is a JToggleButton, which if you press it again, it stops trying to connect, or breaks off the connection if it's already connected. I thought this would be something fairly simple to write, but it seems not, as I'm inundated with errors at every point. I would think this would be a fairly obvious thing to do, but I can't find any examples of anyone else doing anything similar. Can anyone help?
Also, is it good practice to have a while(in.readLine()) loop? This causes my programs to hang, as it's stuck reading input, and not doing other things. So I put all the server code inside a new Thread()... is this the right way to go about things? What do other people do? Thanks for any help!
Here's my server code...
       listenBtn.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                 if(listenBtn.isSelected()) {
                      new Thread() {
                                setDaemon(true);
                           @Override
                           public void run() {
                                logger.info("Listening for a client on port " + portTxt.getText() + "...");
                                try {
                                     server = new ServerSocket(Integer.parseInt(portTxt.getText()));
                                catch(IOException exception) {
                                     logger.warning("Could not listen on port " + portTxt.getText() + ".");
                                try {
                                     client = server.accept();
                                catch(IOException exception) {
                                     logger.warning("Error connecting to client.");
                                if(client != null) {
                                       logger.info("Client connected!");
                                String inputLine, outputLine;
                                try {
                                     out = new PrintWriter(client.getOutputStream(), true);
                                     in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                                catch (IOException exception) {
                                     logger.warning("Error initialising streams.");
                                outputLine = null;
                                out.println(outputLine);
                                try {
                                     while((inputLine = in.readLine()) != null) {
                                          text1.setText(inputLine);
                                          outputLine = text2.getText();
                                          out.println(outputLine);
                                catch(IOException exception) {
                                     logger.warning("Error in input loop.");
                      }.start();
                 else {
                      try {
                           if(out != null) {
                                  out.close();
                           if(in != null) {
                                  in.close();
                           if(client != null) {
                                client.close();
                           if(server != null) {
                                server.close();
                      catch (IOException exception) {
                           logger.warning("Error closing streams or sockets.");
                      logger.info("Listening ended.");
       });And my client code...
           connectBtn.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                 if(connectBtn.isSelected()) {
                   System.out.println("Connecting...");
                   try {
                        socket = new Socket(hostTxt.getText(), Integer.parseInt(portTxt.getText()));
                        out = new PrintWriter(socket.getOutputStream(), true);
                        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   catch (UnknownHostException exception) {
                        System.err.println("Host cannot be identified.");
                        connectBtn.setSelected(false);
                   catch (IOException exception) {
                        System.err.println("Couldn't get I/O for the connection.");
                        connectBtn.setSelected(false);
               if(socket != null) {
                    System.out.println("Connected!");
                   String send, recieved;
                   try {
                        while((recieved = in.readLine()) != null) {
                             intervalTxt.setText(recieved);
                             send = spikesTxt.getText();
                             if(send != null) {
                                  out.println(send);
                   catch(IOException exception) {
                        System.err.println("Error reading input stream.");
                        connectBtn.setSelected(false);
                 else {
                      try {
                           if(out != null)     {
                                    out.close();
                           if(in != null)     {
                                    in.close();
                           if(socket != null)     {
                                socket.close();
                    catch(IOException exception) {
                         System.err.println("Error closing streams or socket.");
                    System.out.println("Connecting ended.");
          });

* In the server, if I click Listen (to search for a client), then I click it again to stop listening (without a client connecting), I get a NullPointerException on this line:
out = new PrintWriter(client.getOutputStream(), true);Obviously 'client' is null.
* Similarly, in the client, when I click Connect when the server is not running, I get a NullPointerException on the line:
while((recieved = in.readLine()) != null) {Obviously 'in' is null.
These are elementary errors. You don't need forums to find them.
* In the server, I want to be able to detect when the client has disconnected or connected. I've got some code that detects when a client has connected, but I'm not sure I'm going about it in the best way.There's only one way. ServerSocket.accept() returns.
And I need some way to detect when a client has disconnected.read() will return -1, readLine() will return null, readXXX() will throw EOFException for any other XXX, or any write method will throw an IOException: connection reset.
* The same thing in the client; I want to know when the server has stopped listeningSee above.
or when the client successfully connects to the server.new Socket(...) returns.
* In the server, I'm doing some OpenGL stuff. As soon as the client connects, the OpenGL stuff stops moving, and becomes totally unresponsive.That will be either because your client session isn't running in a separate thread or it is locked in a hard loop.

Similar Messages

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

  • Two applications wants to read on the same port using Socket

    I have an application running on one machine using TCP/IP socket. The data transfer with the other application on other machine is in ASCII.
    Now I want a new application that can have a copy of data received and sent on the given port, where the previous application is running.
    Is it possible in Java using socket and TCP/IP to have two application reading data from the same port and both can read all the data.

    Even when you don't state the type of app which need to read the data stream (is it a server or a client app???), it's impossible to share a single TCP/IP socket among multiple apps.
    Perhaps the best thing to do is to develop something like a proxy server who listens on the nominated port and provides to contact (if your apps are server ones) or to be contacted (if your apps are client ones) by the desired apps.
    This way, the only job for the proxy is to duplicate the contents of the data stream and make them available to all the apps engaged.
    Hope this helps.

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

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

  • 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;
         }

  • Socket Schema Translation Error when trying to use Socket Adapter in BPEL

    Hi,
    I am trying to use Socket Adapter in BPEL.
    I made 2 SOA Projects
    SOA Application Project 1: Socket Server (Inbound Synchronous Request/Reply). The option for ‘Native Format translation is not required(Schema is Opaque)’ is unchecked .i.e. XSD is given for both request/reply
    SOA Application Project 2: Socket Client (Outbound Synchronous Request/Reply). The option for ‘Native Format translation is not required(Schema is Opaque)’ is unchecked .i.e. XSD is given for both request/reply
    Socket Client which is exposed as Web Service invokes Socket Server.
    1.     <summary>Exception occurred when binding was invoked. Exception occurred during invocation of JCA binding: "JCA Binding execute of Reference operation 'OutboundRequestReply' failed due to: Socket Schema Translation Error. Socket Schema Translation Error. Error while trying to translate from native. Please ensure that the schemas are set up with native annotations and comply with the output XML. Contact Oracle support if error is not fixable. ". The invoked JCA adapter raised a resource exception. Please examine the above error message carefully to determine a resolution. </summary>
    <part name="detail">
    <detail>Read timed out</detail>
    </part>
    Has anybody faced this issue?

    Hi guys:
    I got exactly the same error. I recently installed BPEL Process Manager for Developers 10g Release 2 (10.1.2) in windows XP.
    The default setting for BPEL VM memory is Xms512m -Xmx512m -Xmn300m. I tried to set maximum size to 1024 but I had this error.
    Error occurred during initialization of VM
    Could not reserve enough space for object heap
    if any body can suggest a solution will be great .
    Thanks.
    Message was edited by:
    user533906
    Message was edited by:
    user533906

  • Communication between Windows 7 and Windows 8(and above) using Sockets(TCP and UDP)

    I need to use TCP and UDP using Sockets to communicate between two(or more) applications installed in Windows 7 and Windows 8.
    Is it possible.? I tried within a LAN, but in vain. If needed I would post the appropriate code.
    Note: I only tried running exe(s) in these machines and not with installation.

    Hello Prabodh.Minz,
    >>Is it possible.?
    It is not clear what develop language you are using, here are examples which uses the C# based on .NET. It created the communition between two machines by using sockets with TCP protocol, a server and a client:
    Synchronous example:
    Client and
    Server.
    Asynchronous example:
    Client and
    Server.
    Multi-client per one server - socket programming in .net(C#)
    >>Note: I only tried running exe(s) in these machines and not with installation.
    There are all .exe.
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • File transfering using Sockets

    can anybody help me to find the simple sample code for file transfering. i m new to java and having problem in client server assignment. sending message (chatting) is done, but i still need file transfering part. only one file at one time is good enough.
    thanks.
    moe

    Since you're asking for help with your homework, I won't give you any code but I will point you in the right direction. Sockets can be used to stream data and files also use sockets. If you put the two together, you'll be able to stream your files between JREs.
    Shaun

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

  • How to open multi-windows to operate a remote compute using socket

    hi, please help me.
    I want to develop a program, it can open multi-windows to operate the remote comput at one time just like NetTerm. It use socket to setup connection with remote computer.
    Now I am using a Thread class to setup socket connection with computer, and use Thread's static varible to control all kinds of action of socket.But it can work only when openning one window,because all the thread instances share the same static variable.
    How to do it? Not using Thread? Then the frame will be frozen.
    All adivse are welcomed.Thank you.

    Maybe I don't say it clearly.The program need to show the output of the socket in the JTextArea and transfer the user input to the input of the socket to control the remote computer.

  • Communication between applets using socket

    Hi,
    we have an application in which based on certain criteria a video is bieng played in the applet on same machine.Now we have to separate the video component from the application part so that video can be played separately. they will be communicated using socket.Can any body tell me how to go about for the solution.

    To do this you must have a server application listening to a port on a server box that has a fixed IP. In your Java app, you need to create a Socket connection back to the server (may need to sign your jar - but maybe not)
    voila you're there.
    You may want to search google + these forums for my InfoFetcher class which is built to grab data from an inputstream and report updates to listeners

  • WAN / Internet application using sockets

    I m making an application which will work on Internet / WAN using sockets.
    Now when I want to communicate (e.g. sending a string ) from one node to another over the internet using UDP, it is successfully send.
    When I do the same using TCP, there's a CONNECTION RESET exception on the SERVER end. (Client gets the stream in this case)
    Some of the other important things are.
    - One node is having public IP. (I confirm it by comparing it with www.whatismyip.com)
    - The other node is, I THINK is private IP, (Behind NAT) (I confirm it by comparing it with www.whatismyip.com)
    UDP works fine if anyone of them is sender or receiver. (Both can send and receive UDP Packets)
    Then why TCP is not working??? theoratically, it should !!!
    Is there any firewall issue???
    Is there any NAT issue???
    Plz Answer !!!

    You are quite to build a proxy server :)
    Sockets in java are implemented by SocketServer and Socket class in java.net package. Other useful classes for ip address manipulation are InetAddress and InetSocketAddress. I hope this answer to your first question.
    To answer to your second question I think the simplest way is to design the program to act as a proxy server. The main reason is due to the fact that browsers or other internet application could interact easyly with a proxy and there are clear specification of about it works.
    The concept is that a client application connects (using sockets) to a server program (your proxy) that redirects the request to the real url. Having control of socket streams it could act in some ways to:
    1) allow o deny internet access.
    2) measure time.
    3) filter connection requests to a black listed sites.
    It's hard to explain all technical details here... but you can found sorce code of Open Source implementation at http://sourceforge.net/projects/wpg-proxy/ for a HTTP proxy server and http://jsocks.sourceforge.net/ for a socket proxy. You could start from here to implement your own server.

  • Reading / Writing files using Sockets

    Hi there guys,
    I am fairly new to this forum. I have been having a problem for the past three days. I am implementing a client/server implementation using Sockets which is a submodule of a project I am working on. What I want is that a files content are read and transferred over the network to the server that writes it down to a different file .
    What the code presently does is :
    <<<<Client Code >>>>
    It reads a file input.txt and sends the content over the network to the server.
    <<<< Server Code >>>
    It reads the incoming data from the client and writes the data out to a file called output.txt
    What I want now is that the server should read the file output.txt and send the contents to the client which reads it and then writes it down as a new file called serverouput.txt . After that I want to compare and see of the size of input.txt and serveroutput.txt . If both are same that means that data has been written reliably to the server.
    I have been trying to implement it for a long time and nothing seems to work out. I am posting the code for both client and server below. Any help in finalising things would be really appreciated.
    CLIENT CODE
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Date;
    import java.io.*;
    import java.net.*;
    class sc {
    static final int PORT = 4444;          //Change this to the relevant port
    static final String HOST = "127.0.0.1";
         //Change this to the relevant HOST,
    //(where Server.java is running)
    public static void main(String args[]) {
    try {
    System.out.print("Sending data...\n");
    Socket skt = new Socket(HOST, PORT);
                   // Set the socket option just in case server stalls
    skt.setSoTimeout ( 2000 );
                   skt.setSoKeepAlive(true);
    //Create a file input stream and a buffered input stream.
    FileInputStream fis = new FileInputStream("input.txt");
    BufferedInputStream in = new BufferedInputStream(fis);
    BufferedOutputStream out = new BufferedOutputStream( skt.getOutputStream() );
    //Read, and write the file to the socket
    int i;
    while ((i = in.read()) != -1) {
    out.write(i);
    //System.out.println(i);
                   // Enable SO_KEEPALIVE
    out.flush();
    out.close();
    in.close();
    skt.close();
    catch( Exception e ) {
    System.out.print("Error! It didn't work! " + e + "\n");
              catch( IOException e ) {
    System.out.print("Error! It didn't work! " + e + "\n");
    SERVER CODE
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Date;
    import java.io.*;
    import java.net.*;
    class ClientWorker implements Runnable {
    private Socket client;
    ClientWorker(Socket client) {
    this.client = client;
    public void run(){
    try      {
    FileOutputStream fos = new FileOutputStream("output.txt");
    BufferedOutputStream out = new BufferedOutputStream(fos);
    BufferedInputStream in = new BufferedInputStream( client.getInputStream() );
    //Read, and write the file to the socket
    int i;
    while ((i = in.read()) != -1) {
    out.write(i);
    //System.out.println(i);
    System.out.println("Receiving data...");
    out.flush();
    in.close();
    out.close();
    client.close();
    // srvr.close();
    System.out.println("Transfer complete.");
    catch(Exception e) {
    System.out.print("Error! It didn't work! " + e + "\n");
    class ss1 {
    ServerSocket server = null;
    ss1(){ //Begin Constructor
    } //End Constructor
    public void listenSocket(){
    try{
    server = new ServerSocket(4444);
    } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
    while(true){
    ClientWorker w;
    try{
    w = new ClientWorker(server.accept());
    Thread t = new Thread(w);
    t.start();
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    protected void finalize(){
    //Objects created in run method are finalized when
    //program terminates and thread exits
    try{
    server.close();
    } catch (IOException e) {
    System.out.println("Could not close socket");
    System.exit(-1);
    public static void main(String[] args){
    ss1 frame = new ss1();
         frame.listenSocket();
    }

    ............................................. After that I want to
    compare and see of the size of input.txt and
    serveroutput.txt . If both are same that means that
    data has been written reliably to the server.You don't need to do this. TCP/IP ensures the reliable transmition of data. By using a socket you are automaticaly sure that the data is reliably transmitted (Unless there is some sort of exception).
    To get the size of the files you can use a File object. Look it up in java.io package in API documentation.
    java-code-snippet (without error checking)
    File clientFile = new File("input.txt");
    clientFile.length();

Maybe you are looking for

  • Boxes around text

    hi again, well im slowly getting there with my site, im not really to sure how to explain what id like to do but here goes, on my site i have text in an editable area, that area has a background image, id like the text to be in a box which is a diffe

  • If statements with a String  ????

    hi, im using a JSP page which takes in a username and password and that info is then sent to a servlet which connects to the database and checks to see which type of user they are. the servlet then redirects them to the page that corresponds to the t

  • Release of Solaris 8 (intel)

    When was solaris 8 (intel) released? And what was the previous version.

  • SSH Pasting Passwords

    I have over 30 sites i maintain and update via terminal and SHH. For security reasons my isp has just imposed a new password regime with long convoluted passwords. Is there any way to get terminal to accept pasted passwords?

  • Getting message as request Obsolete in DTP

    Hi  gurus, I can load data till PSA  and request is green. When I try to load data from PSA to info-object master data using DTP , I am getting message request is obsolete. DTP request is showing green but 0 records though there are 2 records in PSA.