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

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

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

  • Network and socket programming in python

    i want to learn network and socket programming but i would like to do this in python.Reason behind this is that python is very simple and the only language i know . 
    anybody can suggest me which book should i pick.
    the book should have following specification--
    1)not tedious to follow
    2)lots of example
    3)starts with some networking stuff and then get into codes
    thanks in advance with regards.

    hmm. well, your requirements are almost contradictory.
    Not sure about books, except maybe dusty's.
    Most python books cover at least some network programming (unless the book is topic specific).
    I use lots of python-twisted at work. I mean ALOT. I wouldn't recommend it to someone looking for non-tedious though! I also like gevent/eventlet (esp. the async socket wrappers).
    EDIT: Wow. My post wasn't really helpful at all. Sorry!
    Last edited by cactus (2010-09-04 09:16:54)

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

  • AE using socket to import picture from URL - Need Your Help

    I have a project that works with local network using the path name. I want to update the project to replace all placeholders with a picture located at a URL address instead of the local network. I have no experience with socket coding and can't seem to find the right snippets of code on the internet to get me through this point of using URL as a file location.
    I tried this code (using a picture at this URL as an example);
    webConnect= new Socket;
    if(webConnect.open("http://distilleryimage3.s3.amazonaws.com")) {
             webConnect.write('GET /2940b7e0236511e2af9022000a1f9a23_7.jpg HTTP/1.0nn');
              response=  webConnect.read();
              webConnect.close();
              alert('complete');
    } else {
             alert('fail');
    Any help will be appreciated. I need the results of the socket connection to be a object I can use in the statement
    curItem.replace(new File( <picture path> );
    Thanks again.

    OK, this comes close to working. I can read the jpg file with QuickTime, though it is corrupted and the image is different color or hue. Nothing else will read the jpg file, it so my efforts to use After Effects have still not been met.
    I have not idea why I have to read 1 byte at the beginning of the data set and discard it. I can't find enough information about the jpg header format but it seems there is corruption at the top of the downloaded file. Since I'm downloading the 'contentLength', it's odd that midstream I get corrupted data. It appears to be consistent too.
    Anyway, I am about at a lose.
    webConnect
    = new Socket;
    if(webConnect.open( "distilleryimage5.s3.amazonaws.com:80","binary")) {
    webConnect.write('GET /distilleryimage5/17bdfa64237411e2a23c22000a1f9d66_7.jpg HTTP/1.0\n\n');
         var file= new File("httpSocket.jpg");
         file.encoding='BINARY'
         file.open ("w","binary");
    var contentLength = ""
    var statusCode = ""
    for (var i = 0; i < 20; i++){
         var response =  webConnect.readln();
         if (new RegExp(/HTTP\/[0-9.]+\s([0-9]+)/).test(response)){
              statusCode = parseInt( new RegExp(/HTTP\/[0-9.]+\s([0-9]+)/).exec(response)[1]);
         else if (new RegExp(/Content-Length: ([0-9]+)/).test(response) ){
              contentLength = parseInt( new RegExp(/Content-Length: ([0-9]+)/).exec(response)[1]);
         else if (new RegExp(/Server: AmazonS3/).test(response) ) {
      break;
    if (statusCode != 200) webConnect.close()
    else{
    alert('statusCode=' + statusCode + ' contentLength=' + contentLength);
        var data = webConnect.read(1);
    var data = webConnect.read(contentLength);
    file.write(data);
         file.close();
         file.execute();

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

  • 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();

  • Client/server application using sockets

    Hi there,
    I'm trying to create a client/server application using sockets where the client has a GUI of a membership application form for some sort of club. Basically, the user will enter their name, address, membership no. etc in to various Jtext fields and then press a JButton to submit these details to the server. The server will then hopefully just dump these details to a text file.
    Can anyone give me any examples, ideas on how to start, links etc.
    Thanks v. much in anticipation,
    Nick

    Take a browse of the tutorial on sockets: http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html

  • Client & server can use different language when using socket for client/ser

    When building client/server applications using socket , is it that client and server do not need to use both Java as long as they implement the same networking protocol?
    Thanks a lot!

    thank you, DrClap!

  • Filestreaming using sockets

    I have written a server and a client for streaming a file. Client to server. I have tried a lot of code to get a file streamed from client to server, but either nothing happens or it's only 16 kb (byte array) arriving and the last result - the server keeps writing (never stops) to the file output making the file grow rapidly and far beyond the size of the transmitted file. I know that file streaming should be the same whether it's local file handling or using sockets. I have the local file streaming working fine, but converting it to sockets doesn't work. So this server/client is a new approach using byte array. Still doesn't work. Can anyone help? Alternatively give me a link to a working code for this job. Thank you. :)
    Client
    import java.io.*;
    import java.net.Socket;
    public class my_client {
         public static void main(String[] args) throws IOException{
                   String server = args[0];
                   int port = Integer.parseInt(args[1]);
                   String filename = args[2];
                   Socket socket = new Socket(server, port);
                   System.out.println("Connected at " + socket.getLocalSocketAddress());
                   OutputStream fout = socket.getOutputStream();
                   FileInputStream bis = new FileInputStream(filename);
                   byte[] data = new byte[1024];                         
                   int totalTx = bis.read(data);          
                   while(totalTx != -1){
                        fout.write(data, 0, totalTx);
                        fout.flush();
                   socket.shutdownOutput();
                   socket.close();
    }Server
    import java.net.*;
    import java.io.*;
    public class my_server {
         public static void main(String[] arg) throws IOException{
              if(arg.length != 1) throw new IllegalArgumentException("Parameter: <port>");
         int servPort = Integer.parseInt(arg[0]);
         ServerSocket servSock = new ServerSocket(servPort);
         while(true){
              Socket clntSock = servSock.accept();
              SocketAddress clntAddress = clntSock.getRemoteSocketAddress();
              System.out.println("Handling client at " + clntAddress);
              InputStream in = clntSock.getInputStream();
              FileOutputStream fout = new FileOutputStream("incomming.txt");
              byte[] data = new byte[1024];
              int totalRx = in.read(data);
              while(totalRx != -1){
                   fout.write(data, 0, totalRx);
              fout.close();
              in.close();
              clntSock.close();
    }

    1. Your read are outside your while loops.
    2. There is a whole protocol standard for file transfer called FTP = File Transfer Protocol.
    3. There is also a networking forum where socket questions are best asked.
    4. Your sever is single threaded so you can only handle one read at a time.

  • Folder transfer using sockets

    Is there anyway to transfer the whole folder including the subfolders
    using sockets.
    i can transfer the all the files one by one
    but it needs lot of coding like making subfolders in the destination and etc.
    i need to send a folder using a single outputstream
    Thanks
    Ananth

    Ananthakumaran wrote:
    tar and untar will take some time Really? Have you measured that?
    I'll bet if you look, the time it takes is completely dominated by the need to read the files on one side and write the files on the other. Since any copy program has to do the same thing, this should be no slower than any other method.
    and mostly my app is used to transfer large size file
    i need something which can send folder like a single file without any >>> overhead >>>Everything you do has overhead. You want to send files and folders over the network. Using tar to serialize that structure has very little overhead. I doubt the overhead will be visible given the need to actually read and write the files.
    Darren

  • How can i taransfer an image over network through Sockets

    If any one have the exsperience for tranfering the image over the network by using socket plz help me immediatly

    You have to write a Server application and a Client application.
    And connect the Client to the Server.
    Then you can send whatever you want in either direction.

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

  • Is there a way to create a virtual network using C# and the Azure SDK/API?

    I don't see a clear way to create an Azure Virtual Network using the SDK.
    I have all the methods to create the virtual network configuration, but no way to submit it:
    IList<string> VirtualNetworkAddressPrefixes = new List<string>();
    IList<string> LocalNetworkAddressPrefixes = new List<string>();
    IList<NetworkListResponse.DnsServer> DNSServers = new List<NetworkListResponse.DnsServer>();
    IList<NetworkListResponse.Subnet> Subnets = new List<NetworkListResponse.Subnet>();
    NetworkListResponse.Gateway Gateway = new NetworkListResponse.Gateway();
    IList<NetworkListResponse.LocalNetworkSite> LocalSites = new List<NetworkListResponse.LocalNetworkSite>();
    IList<NetworkListResponse.Connection> Connections = new List<NetworkListResponse.Connection>();
    VirtualNetworkAddressPrefixes.Add("a.b.c.d/cidr");
    DNSServers.Add(new NetworkListResponse.DnsServer() { Name = "TestDNS1", Address = "a.b.c.d" });
    Subnets.Add(new NetworkListResponse.Subnet() { Name = "Subnet-1", AddressPrefix = "a.b.c.d/cidr" });
    Subnets.Add(new NetworkListResponse.Subnet() { Name = "GatewaySubnet", AddressPrefix = "a.b.c.d/cidr" });
    Connections.Add(new NetworkListResponse.Connection() { Type = LocalNetworkConnectionType.IPSecurity });
    LocalNetworkAddressPrefixes.Add("a.b.c.d/cidr");
    LocalSites.Add(new NetworkListResponse.LocalNetworkSite()
    Name = "On-Prem",
    Connections = Connections,
    VpnGatewayAddress = "a.b.c.d",
    AddressSpace = new NetworkListResponse.AddressSpace() { AddressPrefixes = LocalNetworkAddressPrefixes }
    Gateway.Sites = LocalSites;
    Gateway.Profile = GatewayProfile.ExtraLarge;
    NetworkManagementClient netMgmtClient = new NetworkManagementClient(CloudCredentials);
    NetworkListResponse netlistresp = GlobalSettings.mainWindow.netMgmtClient.Networks.List();
    netlistresp.VirtualNetworkSites
    .Add(new NetworkListResponse.VirtualNetworkSite()
    Name = "TestVirtualNetwork",
    AddressSpace = new NetworkListResponse.AddressSpace() { AddressPrefixes = VirtualNetworkAddressPrefixes },
    DnsServers = DNSServers,
    Subnets = Subnets,
    AffinityGroup = "East US",
    Gateway = Gateway,
    Label = "LabelValue"
    I have also created the entire XML response and sent it to the NetworkManagementClient -> Networks.SetConfiguration() method, but it appears this command expects the virtual network to already be in existence. If anyone could give guidance, it would be
    appreciated.

    Hi,
    As discuss above , we have to create the XML response  ,before that first you have to
    GetConfiguration() details of existing virtual network. 
    string.format("@<NetworkConfiguration xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration'>
                <VirtualNetworkConfiguration>
                <Dns />
                <VirtualNetworkSites>
                <VirtualNetworkSite name=""{0}"" Location=""{1}"">
                <AddressSpace>
                <AddressPrefix>10.0.0.0/8</AddressPrefix>
                </AddressSpace>
                <Subnets>
                <Subnet name=""Subnet-2"">
                <AddressPrefix>10.0.0.0/11</AddressPrefix>
                </Subnet>
                </Subnets>
                </VirtualNetworkSite>",Networkname,location)+(@"<VirtualNetworkSite name=""demodsf1"" Location=""West Europe"">
            <AddressSpace>
              <AddressPrefix>10.0.0.0/8</AddressPrefix>
            </AddressSpace>
            <Subnets>
              <Subnet name=""Subnet-1"">
                <AddressPrefix>10.0.0.0/11</AddressPrefix>
              </Subnet>
            </Subnets>
          </VirtualNetworkSite>  </VirtualNetworkSites>
                </VirtualNetworkConfiguration>
                </NetworkConfiguration>")
    you have to append the node for existing node with new values , i got it its adding new virtual network 
    Best regards,

Maybe you are looking for

  • Using Mini DVI to VGA adapter on MacBook

    I bought the adapter from Apple & hooked up my LCD monitor to the MacBook, but the video I get on the monitor is different that on my laptop. It has an old screen background & the dock but nothing on my desktop shows up. Also, when I'm plugged to the

  • External Hard Drives will not Mount

    I have a WD & LaCie external hard drives in my iMac G5 they have been working fine until I started using the new Time Machine program. Now the drive show up in disk utility but not on the desktop. Disk utility has been no help in repairing them and i

  • Run windows 7 on external hard drive?

    I'm purchasing a MAC mini to replace my G4 and PC. I would like to have Windows available for several applications (mainly for the kids) and am wondering if I could install windows on an external hard drive and run it through the Mini. I really don't

  • To get current Fiscal Week

    Hello Guru's , I have a infoobject (Fiscal Week) which is developed in the back end. In report i would like to get the "Fiscal Week that justed ended" based on the "Fiscal Week" infoobject. Example: Fiscal Week 1,2,3,4,5,6....53 is stored in the cube

  • Configuring Default Web Application w/ WLS6.0 SP2

              I have 2 Machines with no shared file system.           I have identical directory structures on both:           /usr/local/weblogic/config/qadomain/applications/DefaultWebApp           I have 2 Servers within the cluster:           ServerA