Write to socket latency improvements

Hello,
I have an application receiving events, and reacting to them by sending a message to a server through sockets / TCP...
I'm trying to reduce the time between the reception of the event and the confirmation the message has been sent.
right now I'm interested in the part writing on the socket:
    public void sendRawMessage(String msg) {
    try {
        _connection.send(msg);
    catch(java.io.IOException ioe) {
        ioe.printStackTrace(System.out);
}and my 'connection' object:
_socket = new Socket(_host, _port);
_socket.setSoTimeout(3000);           
_out = new DataOutputStream(new BufferedOutputStream(_socket.getOutputStream()));
public void      send(String msg) throws IOException {
    if (!_exit) {
     _out.writeBytes(msg);
        _out.flush();
}I'm measuring the time elapsed before and after my sendRawMessage method (with System.nanoTime())
the machine is a HP x86 server dual cpu, quad core 3GHz, running Solaris x86, Gigabit Ethernet, and the server I'm sending my messages to is running on the same machine.
I get an average of 60us for messages around 180 bytes long, and trying to improve that, as I'm hearing people getting much better results for similar tasks...
CPU usage average is close to 0% along the life of the application, so ressources are available, not too clogged up. I imagine the improvement should come for better coding or configuration of the server / TCP stack, and asking the gurus here for help :-)
do you have any idea or any ressource to point me towards ?
thanks

This is what I get, what do you get:
java -server Loopback1000000 messages in 3004 ms
1000000 messages in 2752 ms
1000000 messages in 2706 ms
1000000 messages in 2728 ms
import java.io.*;
import java.net.*;
public class Loopback
    static final int PORT = 6666;
    public static void main(String args[])
     throws Exception
     new Listener().start();
     Socket socket = new Socket("localhost", PORT);
     DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
     int count = 0;
     long start_time = System.currentTimeMillis();
     while (true) {
         out.writeBytes("hello world");
         out.flush();
         if (++count % 1000000 == 0) {
          long now = System.currentTimeMillis();
          System.out.println("1000000 messages in " + (now - start_time) + " ms");
          start_time = now;
    static class Listener
     extends Thread
     ServerSocket server_socket;
     Listener()
         throws IOException
         server_socket = new ServerSocket(PORT);
     public void run()
         try {
          while (true) {
              Socket socket = server_socket.accept();
              InputStream in = socket.getInputStream();
              byte buf[] = new byte[8192];
              while (true) {
               if (in.read(buf) == -1)
                   break;
              in.close();
              socket.close();
         } catch (IOException e) {
          System.out.println("error in listener: " + e);
}

Similar Messages

  • Socket latency

    I am experiancing long round-trip latency when chaining many Solaris processs together with INET blocking sockets. On NT, I see little latency.
    Is there any way of tuning the solaris internals to make the socket respoonse times falster ? Is there an underlying poll timeout I can change ?
    my setup is 4 processes:
    server: has server socket.
    proxy 2: has server socket and client socket to client.
    proxy 1: has server socket and client socket to proxy 2.
    client: has connection to proxy 1
    The client APP sends 40 100byte messages. these are proxied up to the server, which then responds with a 100byte response message for each request. All sockets are blocking with dedicated reader and writer threads. All apps are threaded C++ apps that have been Purify'ed extensively.
    If I run the processes on seperate SOLARIS boxes I see the time difference between the first message sent by the client to the last response recieved at 0.5 of a second ! I soon deduced that this was due to the nagle algorithm my sending an extra few placebo messages after the last response to effectively flush the nagle algorithm. I then got it down to ~300ms.
    I have now tried running with all processes on the same SunFire-880 machine and the timing is still ~300ms. If I do the same on my Pentium IV Win2000 machine I get round-trip times of ~100 ms or less.
    Does anyone know of any issues that affect the response times of sockets ?
    I don't believe this is my code as I can sustain transaction rates of ~6000 requests and responses per second ! This is what makes these small-burst issues so fustrating.
    Neil

    This is what I get, what do you get:
    java -server Loopback1000000 messages in 3004 ms
    1000000 messages in 2752 ms
    1000000 messages in 2706 ms
    1000000 messages in 2728 ms
    import java.io.*;
    import java.net.*;
    public class Loopback
        static final int PORT = 6666;
        public static void main(String args[])
         throws Exception
         new Listener().start();
         Socket socket = new Socket("localhost", PORT);
         DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
         int count = 0;
         long start_time = System.currentTimeMillis();
         while (true) {
             out.writeBytes("hello world");
             out.flush();
             if (++count % 1000000 == 0) {
              long now = System.currentTimeMillis();
              System.out.println("1000000 messages in " + (now - start_time) + " ms");
              start_time = now;
        static class Listener
         extends Thread
         ServerSocket server_socket;
         Listener()
             throws IOException
             server_socket = new ServerSocket(PORT);
         public void run()
             try {
              while (true) {
                  Socket socket = server_socket.accept();
                  InputStream in = socket.getInputStream();
                  byte buf[] = new byte[8192];
                  while (true) {
                   if (in.read(buf) == -1)
                       break;
                  in.close();
                  socket.close();
             } catch (IOException e) {
              System.out.println("error in listener: " + e);
    }

  • Two Socket errors: Socket write and Socket reset

    does anyone know the reasons and remedies for the error
    java.net.SocketException: Software caused connection abort: socket write error
    and
    java.net.SocketException: Connection reset by peer: socket write error
    please reply if someone knows
    thanks

    These are basically the same error triggered in different places.
    This occurs when the other end of the connection closes while the client is still writing to it.

  • How to write a socket in that i have to use an array of ports

    dear all
    Iam doing project in java in that iam using sockets. My problem is i want to keep array of ports in my programming. suppose one port is busy then it automatically take the other port in the array of ports. Please can any body give me the solution how to use that one. Or if any body know any site regrding that please send me. Ill be waiting for your rely.
    regards
    sonali

    Hi Sonali,
    You can use this. To test,
    javac Sockets.java
    java Sockets &
    java Sockets &
    Here I have used only 3 entries in the array. Server sockets bind and and then listen on them. This is for server sockets. You can write the client side part which will be similar to this.
    Hope it helps.
    Regards,
    Giridhar
    import java.net.*;
    public class Sockets
    ServerSocket socket = null;
    int ports[];
    int counter;
    public Sockets()
    counter = 0;
    ports = new int[3];
    ports[0] = 1000;
    ports[1] = 1900;
    ports[2] = 12000;
    public ServerSocket bindSocket()
    int backLog = 50;
    try
    socket = new ServerSocket(ports[counter], backLog, InetAddress.getByName("localhost"));
    System.out.println("server socket bound successfully at port " + ports[counter]);
    return socket;
    catch(BindException e)
    System.err.println("Port " + ports[counter] + "is busy, trying with " +
    ports[++counter]);
    if (counter == ports.length)
    System.out.println("Could not succeed with any port, returning null");
    return null;
    return bindSocket();
    catch(UnknownHostException uhe)
    System.err.println("wrong host name");
    return null;
    catch(java.io.IOException ioe)
    ioe.printStackTrace();
    return null;
    public static void main(String[] args)
    Sockets sockets = new Sockets();
    ServerSocket ss = sockets.bindSocket();
    try
    while(true)
    Socket acc = ss.accept();
    System.out.println("client accepted, break");
    break;
    System.out.println("tested, now closing the socket");
    ss.close();
    catch(java.io.IOException e)
    System.err.println("io exception while closing socket");

  • File transfer, read write through sockets in client server programming java

    Hello All, need help again.
    I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
    Client side
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class XMLSocketC
         public static void main(String[] args) throws IOException
              //Establish a connection to socket
              Socket toServer = null;
              String host = "127.0.0.1";     
              int port = 4444;
              try
                   toServer = new Socket(host, port);
                   } 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 host.");
                System.exit(1);
              //Send file over Socket
            //===========================================================
            BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // File to be send over the socket.
              File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
              // Checking for the file to be sent.
              if (!file.exists())
                   System.out.println("File doesn't exist");
                   System.exit(0);
              try
                   // InputStream to read the file
                   fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee)
                   System.out.println("Problem, kunne ikke lage fil");
              try
                   InetAddress adressen = InetAddress.getByName(host);
                   try
                        System.out.println("Establishing Socket Connection");
                        // Opening Socket
                        Socket s = new Socket(adressen, port);
                        System.out.println("Socket is clear and available.....");
                        // OutputStream to socket
                        out = new BufferedOutputStream(s.getOutputStream());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        //Checking if bytes available to read to the buffer.
                        while( (numRead = fileIn.read(buffer)) >= 0)
                             // Writes bytes to Output Stream from 0 to total number of bytes
                             out.write(buffer, 0, numRead);
                        // Flush - send file
                        out.flush();
                        // close OutputStream
                        out.close();
                        // close InputStrean
                        fileIn.close();
                   }catch (IOException e)
              }catch(UnknownHostException e)
                   System.err.println(e);
            //===========================================================
            //Retrieve data from Socket.
              //BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
              DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
              //String fromServer;
            //Read from the server and prints.
              //Receive text from server
              FileWriter fr = null;
              String frn = "xxx_response.xml";
              try {
                   fr = new FileWriter(frn);
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              try{
                   String line = in.readUTF();                    //.readLine();
                   System.out.println("Text received :" + line);
                   fr.write(line);
              } catch (IOException e){
                   System.out.println("Read failed");
                   System.exit(1);
            in.close();
            toServer.close();
    public class XMLSocketS
          public static void main(String[] args) throws IOException
              //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4444);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
              while (true)
                        try
                             clientLink = serverSocket.accept();
                           System.out.println("Server accepts");
                             BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             // close the link to client
                             clientLink.close();                         
                             // close InputStream
                             inn.close();                         
                             // flush
                             ut.flush();                         
                             // close OutputStream
                             ut.close();     
                             //Sending response to client     
                             //============================================================
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
    }

    SERVER
    import java.net.*;
    import java.io.*;
    public class XMLSocketS
          public static void main(String[] args) throws IOException
                   //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4545);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
                  try
                             clientLink = serverSocket.accept();
                         System.out.println("Server accepts the client request.....");
                         BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             ut.flush();                         
                             //Sending response to client     
                             //============================================================
                             BufferedInputStream ftoC = null;
                             BufferedOutputStream outtoC = null;
                             // File to be send over the socket.
                             File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
                             try
                                  // InputStream to read the file
                                   ftoC = new BufferedInputStream(new FileInputStream(file));
                             }catch(IOException eee)
                             {System.out.println("Problem reading file");}
                             // OutputStream to socket
                             outtoC = new BufferedOutputStream(clientLink.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int noRead;
                             //Checking if bytes available to read to the buffer.
                             while( (noRead = ftoC.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  outtoC.write(buffer, 0, noRead);
                             outtoC.flush();
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
          }CLIENT SIDE
    import java.io.*;
    import java.net.*;
    public class XMLSocketC
              @SuppressWarnings("deprecation")
              public static void main(String[] args)
                   // Server: "localhost" here. And port to connect is 4545.
                   String host = "127.0.0.1";          
                   int port = 4545;
                   BufferedInputStream fileIn = null;
                   BufferedOutputStream out = null;
                   // File to be send over the socket.
                   File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
                   try
                        // InputStream to read the file
                        fileIn = new BufferedInputStream(new FileInputStream(file));
                   }catch(IOException eee)
                   {System.out.println("Problem");}
                   try
                             System.out.println("Establishing Socket Connection");
                             // Opening Socket
                             Socket clientSocket = new Socket(host, port);
                             System.out.println("Socket is clear and available.....");
                             // OutputStream to socket
                             out = new BufferedOutputStream(clientSocket.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int numRead;
                             //Checking if bytes available to read to the buffer.
                             while( (numRead = fileIn.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  out.write(buffer, 0, numRead);
                             // Flush - send file
                             out.flush();
                             //=======================================
                             DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                             BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
                             String str;
                             while(!(str = in.readLine()).equals("EOF")) {     
                                  System.out.println("client : Read line -> <" + str + ">");
                                  outf.write(str);//Write out a string to the file
                                  outf.newLine();//write a new line to the file (for better format)
                                  outf.flush();
                             //=======================================
                             // close OutputStream
                             out.close();
                             // close InputStrean
                             fileIn.close();
                             // close Socket
                             clientSocket.close();
                        }catch (IOException e)
                        {System.out.println("Exception.");}
         Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
    Thanks

  • Write to socket hange the process

    Hi, my program uses sockets. All is fine, but when the other side suddenly shut downs, my process
    stays hung into the write system call. According to pStack, my process is also stuck on the
    close system call (Since it noticed that the other side was shut down). What happeded ? did the process entered some deadlock because trying to close a socket that is trying to write to it??
    I can't even receive any terminating signals, when normally I receive them with no problem.
    Please help!!!

    This is what I get, what do you get:
    java -server Loopback1000000 messages in 3004 ms
    1000000 messages in 2752 ms
    1000000 messages in 2706 ms
    1000000 messages in 2728 ms
    import java.io.*;
    import java.net.*;
    public class Loopback
        static final int PORT = 6666;
        public static void main(String args[])
         throws Exception
         new Listener().start();
         Socket socket = new Socket("localhost", PORT);
         DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
         int count = 0;
         long start_time = System.currentTimeMillis();
         while (true) {
             out.writeBytes("hello world");
             out.flush();
             if (++count % 1000000 == 0) {
              long now = System.currentTimeMillis();
              System.out.println("1000000 messages in " + (now - start_time) + " ms");
              start_time = now;
        static class Listener
         extends Thread
         ServerSocket server_socket;
         Listener()
             throws IOException
             server_socket = new ServerSocket(PORT);
         public void run()
             try {
              while (true) {
                  Socket socket = server_socket.accept();
                  InputStream in = socket.getInputStream();
                  byte buf[] = new byte[8192];
                  while (true) {
                   if (in.read(buf) == -1)
                       break;
                  in.close();
                  socket.close();
             } catch (IOException e) {
              System.out.println("error in listener: " + e);
    }

  • How to read and write on sockets?

    Hi.
    I want to read and write data from sockets, Can anybody help me.
    Regards.
    Bilal Ghazi.

    You need 3 classes. Receiver, RemoteThread and Sender. These classes are not tested by me
    //these classes are on the clientside
    public class Receiver{//listens to connections
    ServerSocket serverSocket = new ServerSocket(port);
    while (...){
    Socket client=serverSocket.accept();//waits for new connection
    RemoteThread thread=new RemoteThread(client);
    thread.start();
    serverSocket.close();
    public class RemoteThread{
    final static int BUSYWAITTIME=10;//10 ms
    Socket socket;
    public RemoteThread(Socket _socket) {
    this.socket = _socket;
    public void run() {
    BufferedOutputStream out = new java.io.BufferedOutputStream(socket.getOutputStream(),socket.getSendBufferSize());
    int inBuffSize=socket.getReceiveBufferSize();
    BufferedInputStream in = new java.io.BufferedInputStream(socket.getInputStream(),inBuffSize);//wait until get enuff
    byte[] buff=new byte[inBuffSize];
    while (...) {
    //read
    while(in.available()<=0 && !stopped){//just wait for it to become ready
    try{wait(BUSYWAITTIME);}catch(InterruptedException e){}
    int readBytes=in.read(buff);
    //do something with the bytes in buff
    //This class is on the clientside
    public class Sender{
    Socket socket = new Socket(host, port);//connects to server
    OutputStream out = socket.getOutputStream();
    PrintWriter outPrinter=new PrintWriter(out,true);
    InputStream in = socket.getInputStream();
    //use out or outPrinter to write to server
    Gil

  • Nonblockin write on socket not wrking

    On SunOS 5.8 write to the socket (ip4) in non-blocking mode returns EINTR after SIGPIPE has been dilivered.
    Return status EAGAIN or EWOULBLOCK is expected according to the documentation.
    ( NT 4 & Linux 6, 7 behavior of code is as expected )
    Non-blocking mode is set:
                   int FileFlags;
                   FileFlags = fcntl( m_Socket, F_GETFL );
                   if( FileFlags < 0 )
                        FileFlags = 0;
                   fcntl( m_Socket, F_SETFL, FileFlags | O_NONBLOCK );
    Library link order:
         -mt -lposix4 -lpthread -lsocket -lnsl
    Any idea ?
    Slav Brkic, ITS Ltd, Toronto
    [email protected]

    ok, apologies to anyone who has read this and gotten a headache from my stupidity... testing with a work collegue, who you can guess called me an idiot, advised that I was trying to use the ip address as known within my home lan, and that I needed to use the ipaddress as seen externally.
    So, looked at my linksys router admin and found the external ip address. Tested pinging to it, all good. BUT, cannot telnet to that ipaddress port of the java server running on the pc.
    So at this point, the problem is not j2me related.... have started another thread to look at THAT problem, when that is solved, I'm sure there will STILL be problems here, or maybe not... so once that link is addressed, I'll come back here.

  • Broken Pipe Error-unable to write to socket for second attempt

    Hello,
    I am opening socket connection wuth C-server program.
    I am able to write and read from socket for first time but when tried to write second time in the same sequence gives broken pipe error.
    As seen in the code initialize() methods works perfectly fine,
    Pipe broken error is encountered for processRequest() method for writeBytes(begnmsg+"\n") method.
    Please suggest solution asap.
    Following is the code
    import java.io.*;
    import java.net.*;
    public class PowerModelClient {
         Socket kkSocket = null;
    BufferedReader in = null;
         PrintWriter out = null;
         DataOutputStream os = null;
              char m_eomChar = '\n';
    public PowerModelClient(){
    try{
    //Opens socket connection with C-server program,
    openConnection();
    System.out.println("connected to server");
    //Sends data base information to C-server program and receives acknowledgement from it.
    String recv = initialize();
    System.out.println("Initialize successful"+recv);
         try{
    // Sleep for a short period of time
         Thread.sleep ( 10000 );
    catch (InterruptedException ie) {}
         System.out.println("Initialize successfu 22l");
    //Sends data base information to C-server program and receives acknowledgement from it.
    processRequest();
    //Closes socket connection
         closeConnection();
         System.out.println("Comesout to do QUIT ");
    catch(Exception e){
         System.out.println("Error in main::"+e.toString());
         public static void main(String[] args) throws IOException {
                             new PowerModelClient();
    Opens socket connection with C-server program,
    public void openConnection() throws IOException{
    try {
                        kkSocket = new Socket("server",port);               os = new DataOutputStream(kkSocket.getOutputStream());
         //out = new PrintWriter(kkSocket.getOutputStream(),true);
    in = new BufferedReader(((java.io.Reader)(new InputStreamReader(kkSocket.getInputStream()))));
         } catch (UnknownHostException e) {
              System.err.println("Don't know about host: server.");
                        System.exit(1);
                   } catch (IOException e) {
                        System.out.println("Couldn't get I/O for the connection to: server."+e.getMessage());
                        System.exit(1);
         Sends data base information to C-server program and receives acknowledgement from it.
         This makes the C program to connect with Database.
         The data send to socket should be tagged between @BEGMSG@\nand @ENDMSG@\n
         Similary data obtained from socket will be tagged between @BEGMSG@\n and @ENDMSG@\n
    public String initialize() throws IOException{
                   int ibyteread = 0;
              String fromServer = "";
              String beginmsg=padString("@BEGMSG@");
              String endmsg = padString("@ENDMSG@");
              String recv = "";
              if (kkSocket != null ) {
    try {
                        // Set the socket timeout for ten seconds
                   //     kkSocket.setSoTimeout(10000);
                                       //String data = padString("INIT\tabcd\tisderssddsdg\tdrtrs1\twetewte");                              os.writeBytes(beginmsg+m_eomChar);
                   in.read();
              os.flush();
              os.writeBytes(data+m_eomChar);
              in.read();
         os.flush();
         os.writeBytes(endmsg+m_eomChar);
         os.flush();
         recv = readResponse(in);
    } catch (UnknownHostException e) {
    System.err.println("Trying to connect to unknown host: " + e);
                                                 // Exception thrown when network timeout occurs
                             catch (InterruptedIOException iioe)
                             System.err.println ("Remote host timed out during read operation");
                             catch (IOException e) {
                             System.err.println("IOException: " + e);
                             catch (Exception e) {
                   System.err.println("Exception: " + e);
              return recv;
    Sends data after database connection is established to socket for entitlement processing
    and will receive acknowledgement from server.
    public void processRequest() throws IOException{
                   int ibyteread = 0;
                   String beginmsg=padString("@BEGMSG@");
                   String endmsg = padString("@ENDMSG@");
                   String fromServer = "";
              if (kkSocket != null ) {
                   System.out.println("processRequest");
    try {
                             kkSocket.setSendBufferSize(1024);
                             kkSocket.setSoTimeout (10000);
                                       kkSocket.setTcpNoDelay(true);
         os.writeBytes(beginmsg+m_eomChar);
         int i = in.read();
         System.out.println("Data read is :"+i);
         os.writeBytes(padString("PAEL\t1056209\t269732\t02/01/2003")+m_eomChar);
    in.read();
    System.out.println("Data read is :"+i);
    out.flush();
    System.out.println("Data read is :"+ibyteread);
    os.writeBytes(endmsg+m_eomChar);
    ibyteread = in.read();
    readResponse(in);
    System.out.println("-----end Processing:--------");
    } catch (UnknownHostException e) {
    System.err.println("Trying to connect to unknown host: " + e);
    // Exception thrown when network timeout occurs
    catch (InterruptedIOException iioe)
    System.err.println ("Remote host timed out during read operation");
    catch (Exception e) {
    System.err.println("Exception: " + e);
    The socket requires data to be of length 1024 character, so the renaining length is padded with empty string"\0"
    public String padString(String value){
              StringBuffer strBuff = new StringBuffer(value);
                   while(strBuff.toString().length() != 1023){
                   strBuff.append("\0");
              //System.out.println("the length is "+ strBuff.toString().length());
              return strBuff.toString();
    Close socket
    public void closeConnection() throws IOException{
         in.close();
         os.close();
         kkSocket.close();
    public String readResponse(BufferedReader in) {
    boolean flag = false;
              java.lang.StringBuffer stringbuffer = new      StringBuffer(1024);
    try {
    // for(char ac[] = new char[1]; in.read(ac, 0, 1) != -1;) {
    char ac[] = new char[1024];
    if (in.read(ac, 0, 1) != -1) {
    stringbuffer.append(ac[0]);
    for(; in.read(ac, 0, 1) != -1 && ac[0] != m_eomChar; stringbuffer.append(ac[0]));
    if(ac[0] == m_eomChar) {
    System.out.println("received '" + stringbuffer.toString() + "'");
    } else {
    System.out.println("Message received by client was not properly terminated and was ignored."+stringbuffer.toString());
    } else {
    System.out.println("WARN: no response?");
    } catch(java.io.IOException ioexception) {
    System.out.println("Error in client " + ioexception + "Killing client.");
              return stringbuffer.toString();

    if I were you I would put the lines
    kkSocket.setSendBufferSize(1024);
    kkSocket.setSoTimeout (10000);
    kkSocket.setTcpNoDelay(true);
    before connecting to the server, not after the initial message was sent.

  • NOkia 6600 cannot write over socket

    Hi,
    I m new to j2me development. I m curtrently developing on nokia 6600. I m accessing my webserver using emulator and prefectly read and write data on socket connection. When i deploy this program on N6600, the socket connection is established successfully. After getting connection i write on stream and watiing for the response from server. Here the problem comes when i write on server the data is not written on socket and hence no reponse comes and my application blocks.
    I m writing string bytes on socet outputstream. I seprate this connection code in another thread but still the problem exist.
    i dont know what the problem is its URGENT i really need help....

    Hi,
    Did you flushed your output stream (see OutputStream.flush) ?
    Hope that help,
    Jack

  • [CLOSED] evolution freezing; endlessly attempting to write to socket

    For some reason Evolution has decided to start freezing on me... Immediately after start, the main window displays and that's it. If I try to select a different email, the email I click is highlighted, but it doesn't actually display. Double-clicking it to open it in a new window displays the new window, but the message is not loaded.
    A strace of the process shows it is in what appears to be an infinite loop attempting to access a socket:
    writev(3, [{"\230\7\2\0\37rb\0026\0\2\0\36rb\0025\30\4\0000rb\2\n\0`\2\220\6\336\2"..., 5976}, {NULL, 0}, {"", 0}], 3) = 5976
    recvfrom(3, 0x1cfbaf4, 4096, 0, 0, 0) = -1 EAGAIN (Resource temporarily unavailable)
    poll([{fd=4, events=POLLIN}, {fd=3, events=POLLIN}, {fd=5, events=POLLIN}, {fd=9, events=POLLIN}, {fd=8, events=POLLIN}], 5, 0) = 0 (Timeout)
    poll([{fd=4, events=POLLIN}, {fd=3, events=POLLIN}, {fd=5, events=POLLIN}, {fd=9, events=POLLIN}, {fd=8, events=POLLIN}], 5, 0) = 0 (Timeout)
    recvfrom(3, 0x1cfbaf4, 4096, 0, 0, 0) = -1 EAGAIN (Resource temporarily unavailable)
    poll([{fd=4, events=POLLIN}, {fd=3, events=POLLIN}, {fd=5, events=POLLIN}, {fd=9, events=POLLIN}, {fd=8, events=POLLIN}], 5, 0) = 0 (Timeout)
    recvfrom(3, 0x1cfbaf4, 4096, 0, 0, 0) = -1 EAGAIN (Resource temporarily unavailable)
    recvfrom(3, 0x1cfbaf4, 4096, 0, 0, 0) = -1 EAGAIN (Resource temporarily unavailable)
    poll([{fd=4, events=POLLIN}, {fd=3, events=POLLIN}, {fd=5, events=POLLIN}, {fd=9, events=POLLIN}, {fd=8, events=POLLIN}], 5, 0) = 0 (Timeout)
    recvfrom(3, 0x1cfbaf4, 4096, 0, 0, 0) = -1 EAGAIN (Resource temporarily unavailable)
    poll([{fd=4, events=POLLIN}, {fd=3, events=POLLIN}, {fd=5, events=POLLIN}, {fd=9, events=POLLIN}, {fd=8, events=POLLIN}], 5, 0) = 0 (Timeout)
    poll([{fd=3, events=POLLIN|POLLOUT}], 1, -1) = 1 ([{fd=3, revents=POLLOUT}])
    This is on an up to date Arch x86_64 machine; fully updated since I hoped that would solve the problem. It was working fine this morning, but has now decided it doesn't like me
    Any ideas folks?
    Last edited by fukawi2 (2012-04-17 03:17:17)

    Seems to be a problem with a particular email; after a backup and restore of email the problem was still present. After deleting the last email I received, the problem is gone :-|

  • Sockets write/close operations hangs application

    Hi!
    I've got a trouble with my web-application. It'a s chat system, that uses Keep-Alive connections for messages output and that recieves messages through another socket.
    Everything is fine with receiving messages. But after message is received, I need to send it to all recepients. So, I use Socket.write() method. If writing is failed, or user is logged off, I use Socket.close().
    Problem is, that sometimes Socket.write() and Socket.close() are blocking their threads.
    How can I avoid such a blocking behaviour?
    If I'll rewrite everything to use not sockets, but socket channels, can it help to solve my problem?
    Thanks.

    If writes are blocking it can only mean that readers aren't reading. Fix that, and forget about the syncrhonization suggestion which is nonsense.
    You can also use NIO in non-blocking mode to avoid blocking in writes, and it does lead to more scalable applications, but be prepared for about a 10x increase in complexity.

  • How can i create a socket connection through an http proxy

    i'm trying to make a socket connection send an email - i have code that works when you don't have to go through a proxy server but i can't make it pass the proxy server.
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Mail
    public String to_address = "[email protected]";
    public String from_address = "[email protected]";
    public String sendSub = "HeHeHe";
    public String sendBody = "hehehe - it worked";
    // This is created to allow data to be read in by the keyboard.
    BufferedReader in = new BufferedReader(
    new InputStreamReader(System.in));
         private void Mail(String to_address, // recipient's addresses
    String from_address, // sender's address
    String sendSub, // subject
    String sendBody) // Message
                   throws IOException, ProtocolException,      UnknownHostException {
         Socket socket;                // creates a Socket named socket
         PrintStream out;               // stream to write to socket
         String host = "imap.btopenworld.com";          // identification of the mail server host
    // creates a new socket for connection to the mail server
    // as well as two variables for the read and write streams
         socket = new Socket(host, 25); // opens socket to host on port 25 (SMTP port)
         out = new PrintStream(socket.getOutputStream());
    // read the initial message
         in.readLine();
    // Dialog with the mail server
    // send HELO to SMTP server HELO command is given by a connecting SMTP host
         out.println( "HELO " + host );
         out.flush() ;
         in.readLine();
    // Once we are connected to the mail server we start sending the email...
    // send "from"
         out.println( "MAIL FROM: " + from_address );
         out.flush() ;
         in.readLine();
    // send "to"
         out.println( "RCPT TO: " + to_address );
         out.flush() ;
         in.readLine();
    // prepare the mailserver to receive the data
         out.println( "DATA" );
         out.flush() ;
         in.readLine();
    // Send actual email
         out.println("From: " + from_address);
         out.println("To: " + to_address);
         out.println( "Subject: " + sendSub + "\n" );
         out.flush() ;
         out.println("");
         out.println( sendBody ) ;
         out.println(".") ; // standard to determine end-of-body
         out.flush() ;
         in.readLine();
    //Quit and closes socket
         out.println("QUIT");
         out.flush();
         in.close() ;
         socket.close() ;
         return ;
    public static void main (String [] args) throws IOException
    Mail themail = new Mail();
    }

    i've tried that but it doesn't seem to do nething - this is how i implemented it...
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Mail
    public String to_address = "[email protected]";
    public String from_address = "[email protected]";
    public String sendSub = "HeHeHe";
    public String sendBody = "hehehe - it worked";
    // This is created to allow data to be read in by the keyboard.
    BufferedReader in = new BufferedReader(
    new InputStreamReader(System.in));
         private void Mail(String to_address, // recipient's addresses
    String from_address, // sender's address
    String sendSub, // subject
    String sendBody) // Message
                   throws IOException, ProtocolException,      UnknownHostException {
         Socket socket;                // creates a Socket named socket
         PrintStream out;               // stream to write to socket
         String host = "imap.btopenworld.com";          // identification of the mail server host
    // creates a new socket for connection to the mail server
    // as well as two variables for the read and write streams
         socket = new Socket(host, 25); // opens socket to host on port 25 (SMTP port)
         out = new PrintStream(socket.getOutputStream());
    // read the initial message
         in.readLine();
    System.getProperties().put( "proxySet", "true" );
              System.getProperties().put( "proxyHost", "144.124.16.28" );
              System.getProperties().put( "proxyPort", "8080" );
    // Dialog with the mail server
    // send HELO to SMTP server HELO command is given by a connecting SMTP host
         out.println( "HELO " + host );
         out.flush() ;
         in.readLine();
    // Once we are connected to the mail server we start sending the email...
    // send "from"
         out.println( "MAIL FROM: " + from_address );
         out.flush() ;
         in.readLine();
    // send "to"
         out.println( "RCPT TO: " + to_address );
         out.flush() ;
         in.readLine();
    // prepare the mailserver to receive the data
         out.println( "DATA" );
         out.flush() ;
         in.readLine();
    // Send actual email
         out.println("From: " + from_address);
         out.println("To: " + to_address);
         out.println( "Subject: " + sendSub + "\n" );
         out.flush() ;
         out.println("");
         out.println( sendBody ) ;
         out.println(".") ; // standard to determine end-of-body
         out.flush() ;
         in.readLine();
    //Quit and closes socket
         out.println("QUIT");
         out.flush();
         in.close() ;
         socket.close() ;
         return ;
    public static void main (String [] args) throws IOException
    Mail themail = new Mail();
    }

  • Time to improve...

    Hewwo everyone...
    I lately finely got my hands on the Lumia 800...
    I'm quite satisfied with it, but also disappointed... I was excepting a bit more...
    First, we lately blamed Nokia for the battery life...
    I'm an old Symbian user and new to WP7, but because of this, I noticed a lot of things...
    Before going futher, I want to tell you that I managed to down the battery drop to 57mA...
    Well, only for a short while, but it mean it's possible...
    This post is for both Nokia and Microsoft...
    I will write down here any improvements I thought of, to help things to work better...
    First Microsoft :
    The two first option should help a lot in the battery saving...
    -If no data needed, then data shutdown till it's needed again :
        Even if it's a smartphone, it doesn't mean we need/want to be connected all time along...
        Some people, like me as example, check e-mails only every hours...
        Same for facebook or anything else... Why should we using data when we don't need it?!
        Plus, some people don't use an  expensive mobile plan, and so,
        have like 500Mo data per month... If data is always on, it's a waste...
    -A way to close apps :
        It's now well know, WP7 doesn't really close the apps...
        As result, if we open an app using data, lets say facebook in web-browser,
        it will keep data on, keep updating the facebook page, and of course, kill down the battery
        (Yet I found out that closing tabs was stopping it... But yet should we thought about it...)
        Some other apps don't use data, but still kill down the battery because they're
        not really closed.
        On Symbian, we was able to see all apps in background, and close them if needed.
    -More options on e-mail settings :
        Having a smartphone doesn't mean we don't have a computer...
        Once I'm at home, I have no need for my phone to get my e-mail...
        Actually on WP, we can set the e-mail to be gathered every 30 mins, hours, etc...
        But it's all day along... So, if we receive a e-mail at 2:30am, then the phone will
        gather it at 3am, wakes us up, etc...
        So more options, to set the days, the hours (like between 8am to 5pm) would help a lot...
    -E-mail :
        Be able to send more file format into the e-mail... Like *.pdf files...
    -More options for the camera :
        Some features are missing...
        Black and white, sephia, and more... You know what I mean...
    -Clock :
        Most of people now, have contacts around the world...
        An way to add on or more clock to know time around the world would help...
    -Alarm :
        Almost perfect... An option to set time alarm repeat would be fine...
    -Ringtone improvement :
        Don't blame me if I look mean a bit, but here is what we call a joke...
        Before the smartphone was on the market, we was already able to use the mp3 in
        our phone as ringtone for call, sms, mms, etc..
        So why, please tell me why... Why do we have to take the pain in the *** to edit a mp3,
        cut it to 40 secs max, make it be less than 1Mo, set the type as Ringtone,
        to finely be able to use it that way...
        And yet, we can use them for call only... Not for sms, mms, e-mail, etc...
        I think you already understood where I wanted to come... It's a smartphone...
        All is in the name... does that kind of phone isn't smart enough to simply use
        mp3 like they're as ringtones?! We can except better...
    -Improve Zune music/movie player :
        Yes, I must say that one is a lame... But, that is my own point of view...
        Still, at least an equalizer is missing...
        As it's a WP, maybe thinking about a tag editor for mp3 would be a cool feature...
        Be able, by clicking the time bar, to move at a point on the song...
    -A possibility of background screen behind the tiles :
        Yes, may not sounds useful to you, but seeing a black screen behinds my tiles isn't
        lovely at all...
        In the same time, an option to make tiles transparent...
        So, from no transparency till full transparency, leaving only the icons on the tile...
        So the background would become a bit more useful...
    I guess that is all I have on mind from Microsoft side...
    Second Nokia :
    I won't talk about the battery, as you're already working on your own battery issues...
    -A modem access :
        lost of people have an unlimited data access...
        And therefore, using our phone as modem would help...
        If I'm not wrong, I saw a word about it saying it would come...
    -Bluetooth improvement
        Bluetooth seems to have some issues...
        I can send files from my Lumia to my C7... But don't works from my C7 to my Lumia....
        Also like on most of the Nokia, a menu to see associated peripherals...
        Allow them, block them, etc...
    -Compatibility with Nokia Suite :
        Zune don't have some options like Nokia Suite does...
        Saving contacts, calendar, notes, messages, etc...
        It would also help moving them from an old phone to a new one...
    I spent too much time writing my post, I forgot few things...
    Anyway, it's here a good list of things to change...
    I'm not sure that Microsoft will come here to read that...
    So if anyone know where I should post that so Microsoft would read it, please tell me...
    You may also get few things in mind that need to be improved...
    Please try to keep it ordered, saying if it's for Microsoft, or Nokia...
    Don't flush your anger in this post... This won't help anything...
    Cordially, Jérémie.

    PaulWork wrote:
    I strong believe we need to add more ability in switch – case statements to function similar to multi if-else stmt. It does work like that so what your point is not at all clear.
    Something similar to the one below.
    switch(actionStr){
    case “EDIT”: In the future please use code formatting tags when posting code. All that that code really shows me is that
    a) you want switch to work on Strings
    b) you may not be aware of break which could explain your other confusion

  • Trying to read from a socket character by character

    Hi all,
    I have a problem with reading from a socket character by character. In the code shown below I try and read each character, and then write it to a file. The information sent to a socket sent from a file, and EOF is marked with character of ascii code 28 (file separator). However using BufferedReader.read() I get -1 forever. Is it reading only the last character to have been sent to the socket?
    As a side note, if I use readLine() (making sure the socket is sent a newline at end of msg) I can get the message fine. However, I want to be able to receive a message with 0 or many newlines in it (basically contents of a text file), so I want to avoid the readLine() method.
    Any help at all is appreciated,
    Colm
    CODE SNIPPET:
    try
    serverSocket = new ServerSocket(listenToPort);
    System.out.println("Server waiting for client on port " + serverSocket.getLocalPort());
    while(true)
    inSocket = serverSocket.accept();
    System.out.println("New connection accepted " + inSocket.getInetAddress() + ":" + inSocket.getPort());
    input = new BufferedReader(new InputStreamReader(inSocket.getInputStream()));
    fileOutput = new BufferedWriter(new FileWriter(outputFilename));
    System.out.println("Ready to write to file: " + outputFilename);
    //receive each character and output it to file until file separator arrives
    while(!eof)
    inCharBuf = input.read();
    System.out.print(inCharBuf);
    //check for file separator (ASCII code 28)
    if (inCharBuf == 28) eof = true;
    //inChar = (char) inCharBuf;
    fileOutput.write(inCharBuf);
    System.out.println("Finished writing to file: " + outputFilename);
    inSocket.close();
    catch (IOException e)
    System.out.println("IO Error with serverSocket: " + e);
    System.exit(-1);
    }(tabbing removed as it was messing up formatting)

    My guess is that the code that is writing to the
    socket did not flush it. You said in one case you
    could read it (via readln) if the writer was writing
    lines (writeln flushes, I believe). Are you writing
    the exact same data to the socket in both tests?woo hoo, I hadn't flushed the buffers alright!
    for anyone with similar problems, I was missing this from my write-to-socket method:
    output.flush();
    where output was the BufferedWriter I had created to write to the socket.
    Thanks a lot for pointing it out!
    Colm

Maybe you are looking for

  • My ipod video wouldn't play music anymore

    Today i was listening to my ipod video and it was perfectly fine after an hour, I wanted to listen to it so I went on to artists and clicked on one, then it started skipping through all the songs in that artist and it wouldn't play any music at all!

  • Php email form with styling

    Hi I have a php file which generates an email from a form in a website I have designed. I just want to make some areas of the final generated email in bold text. I know if people have plain text only selected in their email client they won't see the

  • Storage for Foreign Keys and Function based indexes

    This may well be the silliest question of the day, but is it possible to specify the storage for a Foreign key or a function based index? I'm not even sure that it would make sense.

  • Sp3 and pdf export with diadem

    Dear all; We use Diadem 11 with windows XP SP2, and we use the functions PDF and Html Export . After upgrading from pack 2 to windows xp pack 3 we could no longer use these functions. We now the recieve error message : Access Violation r The printer

  • Dynamically add custom MXML components in Actionscript

    As there's no constructor for custom MXML components, how to dynamically add it as a child using ActionScript? I'm looking for some alternative to avoid the need to rewrite the entire existent component in ActionScript just to add it this feature (a