Subsequent drop in no. of Socket connections

Hi All ,
I have created one application which uses lots of threading and socket connections (Both TCP and UDP).
I am using Linux Server with following configuration
1. Quad core processor
2. 8 GB RAM
3. Enough bandwidth for 10,000 simultaneous connections
In this application I need to connect to more than 5000 different Servers at a time. But I could not succeed . The application is quite stable with around 3000-3500 connections and works fine in all aspects.
Now when I tried to connect to 5000 connections it becomes quite unstable .
Initially it was showing that Out of memory Error . Then I changed some VM arguments .
My current VM arguments are
export VM_ARG=" -Xms64m -Xmx1024m "
export VM_ARG=$VM_ARG" -Xss75k "
export VM_ARG=$VM_ARG" -XX:NewRatio=15 "
export VM_ARG=$VM_ARG" -Djava.net.preferIPV6Addresses=false -ea -Djava.net.preferIPv4stack=true "
#export VM_ARG=$VM_ARG" -verbose:gc "
export VM_ARG=$VM_ARG" -XX:+UseParallelGC "Now It doesn't throw the Out of Memory that often but looses the connections quite often .
I think I could not use the all capabilities of my system . Can any one suggest me some better options
Thanks in Advance,
-- Vishal

You should be able to support around 1,000 - 3,000 threads with an up to date version of Linux.
I think you have done very well if you have one thread per connection.
If you want more connections you need to use non-blocking io and then you should be able to cut the number of threads to one or two per CPU.

Similar Messages

  • Java Socket Connection Time out

    Goal*
    I want to check host/port availability of computers in our network (~100 computers) .. Just check if host is alive and if it has port 445 opened. I want to do this somehow in parallel, so the code execution is as quick as possible.
    My implementation*
    I do this by creating socket connection to the host. Something like this:
            Socket s = null;
            try {
                s = new Socket();
                InetSocketAddress socketAddress = new InetSocketAddress(ipAddress, 445);
                s.connect(socketAddress, 3000);
                if (s.isConnected()) {
                    // do something
            } catch (ConnectException ex) {
                //exception thrown
            } catch (IOException ex1) {
                //exception thrown
            } finally {
                try {
                    // close socket
                    s.close();
                } catch (IOException ex) {
                    Logger.getLogger(ComputerModel.class.getName()).log(Level.SEVERE, null, ex);
            }This code is executed in a loop, where a separate thread is created for every iteration = ~100 separate threads.
    Problem:*
    1.
    It seems to me, that first ~10-15 connections are created ok, but then my code reaches 'IOException' catch block for every subsequent itteration and ex.getMessage() returns "connection time out" (I try to use different timeout values in the 2nd parameter. Values from 3000 up to 20000).
    Is it valid to create 100 separate threads in a loop? Can't I make my NIC to bussy with this ??? What is the maximum ammount of threads, I can create? I did not use threads before, so I have no idea, if max values are near to 10, 100, 1000, or 10000 ..
    2.
    After my code is executed, I enter 'netstat -an' command in my command line and I get bunch of connections, which report status of SYN_SENT for several connections.
    TCP 10.20.11.140:4557 10.30.11.119:445 SYN_SENT
    TCP 10.20.11.140:4558 10.30.11.176:445 SYN_SENT
    TCP 10.20.11.140:4559 10.30.11.100:445 SYN_SENT
    TCP 10.20.11.140:4560 10.30.11.142:445 SYN_SENT
    TCP 10.20.11.140:4561 10.30.11.171:445 SYN_SENT
    TCP 10.20.11.140:4562 10.30.11.143:445 SYN_SENT
    TCP 10.20.11.140:4563 10.30.12.12:445 SYN_SENT
    TCP 10.20.11.140:4564 10.30.12.11:445 SYN_SENT
    TCP 10.20.11.140:4565 10.30.12.21:445 SYN_SENT
    TCP 10.20.11.140:4566 10.30.11.150:445 SYN_SENT
    I also feel, that my computer network response (e.g. firefox browsing) is a bit slower ..
    How shall I handle this problem properly?
    Thx in advance,
    Juraj

    kajbj wrote:
    tschodt wrote:
    kajbj wrote:
    The documentation for netstat explains what SYN_SENT is, but
    I don't know why you have them.The app has asked the TCP stack to transmit SYN
    the TCP stack is now waiting for SYN-ACK.
    If there is no host at that IP address or a host that drops connections (SYN packets) for TCP port 445
    there will never be a SYN-ACK.
    After a few minutes the TCP stack will time out the connection attempt.Yes, I was rather commenting on why his hosts aren't answering. I thought that his case was that all of them should answer :)Akkurat. I was answering more for clarification.
    Someone who does not know your posting history could easily assume you meant
    it was a mystery why netstat was showing SYN_SENT.
    And I figured it would not harm to hint that one possible reason would be that those machines are powered off (no host).

  • Establishing a socket connection between a .swf file and a socket-test program (TCP/IP builder - Windows), in AS3.

    I have an issue with a college project I'm working on.
    Using Actionscript 3, I made a simple .swf program, an animated, interactive smiley, that 'reacts' to number inputs in a input-box.
    For the sake of the project, I now need to make the framework for establishing a socket connection with the smiley .swf, and another program.
    This is where I encounter issues. I have very little knowledge of AS3 programming, so I'm not certain how to establish the connection - what's required code-wise for it, that is.
    To test the connection, I'm attempting to use the "TCP/IP builder" program from windows, which lets me set up a server socket. I need to program the .swf file into a client - to recognize it, connect to it, then be able to receive data (so that the data can then be used to have the smiley 'react' to it - like how it does now with the input-box, only 'automatically' as it gets the data rather than by manual input).
    My attempts at coding it are as follows, using a tutorial (linked HERE):
    //SOCKET STUFF GOES HERE
        var socket:XMLSocket;        
        stage.addEventListener(MouseEvent.CLICK, doConnect); 
    // This one connects to local, port 9001, and applies event listeners
        function doConnect(evt:MouseEvent):void 
        stage.removeEventListener(MouseEvent.CLICK, doConnect); 
        socket = new XMLSocket("127.0.0.1", 9001);   
        socket.addEventListener(Event.CONNECT, onConnect); 
        socket.addEventListener(IOErrorEvent.IO_ERROR, onError); 
    // This traces the connection (lets us see it happened, or failed)
        function onConnect(evt:Event):void 
            trace("Connected"); 
            socket.removeEventListener(Event.CONNECT, onConnect); 
            socket.removeEventListener(IOErrorEvent.IO_ERROR, onError); 
            socket.addEventListener(DataEvent.DATA, onDataReceived); 
            socket.addEventListener(Event.CLOSE, onSocketClose);             
            stage.addEventListener(KeyboardEvent.KEY_UP, keyUp); 
        function onError(evt:IOErrorEvent):void 
            trace("Connect failed"); 
            socket.removeEventListener(Event.CONNECT, onConnect); 
            socket.removeEventListener(IOErrorEvent.IO_ERROR, onError); 
            stage.addEventListener(MouseEvent.CLICK, doConnect); 
    // Here, the flash tracks what keyboard button is pressed.
    // If 'q' is pressed, the connection ends.
            function keyUp(evt:KeyboardEvent):void 
            if (evt.keyCode == 81) // the key code for q is 81 
                socket.send("exit"); 
            else 
                socket.send(evt.keyCode); 
    // This one should handle the data we get from the server.
            function onDataReceived(evt:DataEvent):void 
            try { 
                trace("From Server:",  evt.data ); 
            catch (e:Error) { 
                trace('error'); 
        function onSocketClose(evt:Event):void 
            trace("Connection Closed"); 
            stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp); 
            socket.removeEventListener(Event.CLOSE, onSocketClose); 
            socket.removeEventListener(DataEvent.DATA, onDataReceived);
    Trying to connect to the socket gives me either no result (other than a 'connection failed' message when I click the .swf), or the following error:
    Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: file:///C|/Users/Marko/Desktop/Završni/Flash%20documents/Smiley%5FTCP%5FIP%5Fv4.swf cannot load data from 127.0.0.1:9001.
        at Smiley_TCP_IP_v4_fla::MainTimeline/doConnect()[Smiley_TCP_IP_v4_fla.MainTimeline::frame1:12] 

    Tried adding that particular integer code, ended up with either errors ("use of unspecified variable" and "implicit coercion") , or no effect whatsoever (despite tracing it).
    Noticed as well that the earlier socket code had the following for byte reading:
    "sock.bytesAvailable > 0" (reads any positive number)
    ...rather than your new:
    "sock.bytesAvailable != 0" (reads any negative/positive number)
    Any difference as far as stability/avoiding bugs goes?
    So then, I tried something different: Have the program turn the "msg" string variable, into a "sentnumber" number variable. This seemed to work nicely, tracing a NaN for text (expected), or tracing the number of an actual number.
    I also did a few alterations to the input box - it now no longer needs the 'enter' key to do the calculation, it updates the animation after any key release.
    With all this considered and the requirements of the project, I now have a few goals I want to achieve for the client, in the following order of priority:
    1) Have the "sentnumber" number variable be recognized by the inputbox layer, so that it puts it into the input box. So in effect, it goes: Connect -> Send data that is number (NaN's ignored) -> number put into input box -> key press on client makes animation react. I optionally might need a way to limit the number of digits that the animation reacts to (right now it uses 1-3 digit numbers, so if I get sent a huge number, it might cause issues).
    - If the NaN can't be ignored (breaks the math/calculus code or some other crash), I need some way of 'restricting' the data it reads to not include NaN's that might be sent.
    - Or for simplicity, should I just detect the traced "NaN" output, reacting by setting the number variable to be "0" in such cases?
    2) After achieving 1), I'll need to have the process be automatic - not requiring a keyboard presses from the client, but happening instantly once the data is sent during a working connection.
    - Can this be done by copying the huge amounts of math/calculus code from the inputbox layer, into the socket layer, right under where I create the "sentnumber" variable, and modifying it delicately?
    3) The connection still has some usability and user issues - since the connection happens only once, on frame 1, it only connects if I already have a listening server when I run the client, and client can't re-connect if the server socket doesn't restart itself.
    I believe to do this, I need to make the connection happen on demand, rather than once at the start.
    For the project's requirement, I also need to allow client users to define the IP / port it's going to connect to (since the only alternative so far is editing the client in flash pro).
    In other words, I need to make a "Connect" button and two textboxes (for IP and port, respectively), which do the following:
    - On pressing "Connect", the button sets whatever is in the text boxes as the address of the IP and port the socket will connect to, then connects to that address without issues (or with a error message if it can't due to wrong IP/port).
    - The connection needs to work for non-local addresses. Not sure if it can yet.
    - On re-pressing connect, the previous socket is closed, then creates a new socket (with new IP/port, if that was altered)
    It seems like making the button should be as simple as putting the existing socket code under the function of a button, but it also seems like it's going to cause issues similar to the 'looping frames' error.
    4) Optional addition: Have a scrolling textbox like the AIR server has, to track what the connection is doing on-the-fly.
    The end result would be a client that allows user to input IP/Port, connects on button press (optionally tracking/display what the socket is doing via scrollbox), automatically alters the smiley based on what numbers are sent whilst the connection lasts, and on subsequent button presses, makes a new connection after closing off the previous one.
    Dropbox link to new client version:
    https://www.dropbox.com/s/ybaa8zi4i6d7u6a/Smiley_TCP_IP_v7.fla?dl=0
    So, starting from 1), can I, and how can I, get the number variable recognized by "inputbox" layer's code? It keeps giving me 'unrecognized variable' errors.

  • Socket.connect

    I'm trying to write a client application that will connect to a server whenever it becomes available. There are some problems which I hope someone will be able to help, Below is a snippet of the code that makes the connection:
    while(alive){
    try{
    /* part 1*/
    Socket s = new Socket();
    s.setReuseAddress(true);
    s.bind(localAddress);
    /* end part 1*/
    s.connect(targetAddress);
    } catch (Exception e){}
    this seems to works fine. However when I place part 1 of the code outside the while loop. the connection will not be made if the server application is up after my connection thread has started running. Isnt Socket.connect suppose to block until a valid connection is made?
    Also when running my application (with the code above) over a long period of time, I get a OutOfMemoryException (native memory) when the server application is not present. Do I have to specify some other parameters for the JVM to release the native resources allocated for a socket construction or is this just a bug? I am running the application using java 1.6 on RHEL4 2.6.9-34.ELSMP.
    Thank you in advance.

    The thread is respawned when then server application
    drops thus yes the socket will only make one
    connection.Not if you move part 1 out of the loop.If you do that you will attempt multiple connections with the socket, which doesn't work.
    Shouldnt the thread block when .connect() fails?Why? Block doing what?
    Instead i'm getting a connection refused exception.What else should it do?
    No i did not close the socket when I get an exception.You should.
    Should the resources be reclaimed since
    the socket object would have gone out of scope?Eventually.
    I'm running my application on a system with multiple
    network cards thus i need to bind it to the intended
    address.Why? TCP/IP will find the best route if you don't get in its way. Why not let it?

  • Periodic socket connection errors

    I am experiencing a periodic error when accessing a Servlet running under
              weblogic 6 sp2 on Windows 2000. Usually the second time my servlet is
              accessed I see the connection error and then periodically after that. Here
              is the stack trace:
              .lang.NullPointerException
              at weblogic.socket.TunnelContext.getServlet(TunnelContext.java:24)
              at
              weblogic.servlet.internal.MuxableSocketHTTP.dispatch(MuxableSocketHTTP.java:
              465)
              at weblogic.socket.NTSocketMuxer.processSockets(NTSocketMuxer.java:638)
              at weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:23)
              at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              >
              <Oct 1, 2001 9:38:01 PM EDT> <Error> <HTTP> <Connection failure
              java.lang.NullPointerException
              at weblogic.socket.TunnelContext.getServlet(TunnelContext.java:24)
              at
              weblogic.servlet.internal.MuxableSocketHTTP.dispatch(MuxableSocketHTTP.java:
              465)
              at weblogic.socket.NTSocketMuxer.processSockets(NTSocketMuxer.java:638)
              at weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:23)
              at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              I traced this in the debugger and found that the first error occurs before
              my servlet is even invoked. The second error occurs after I try to read
              from the ServletInputStream object. When the error occurs I must kill the
              client request, which hangs, and then subsequent requests are fine.
              I have not seen anything like this in these newsgroups. Does anyone have
              any ideas as to why this is happening?
              Thanks,
              Mark
              

              Hi, I'm facing same problem. Did you guys get a solution for this?
              Thanks,
              Tarkeshwar
              "Mark Priest" <[email protected]> wrote:
              >It sounds like we are both experiencing a similar problem on different
              >platforms. Will someone from Bea please comment on this?
              >
              >Thanks,
              >Mark
              >
              >"Alexis Berger" <[email protected]> wrote in message
              >news:[email protected]...
              >> Mark,
              >>
              >> I currently got the same problem.
              >> my config is Weblogic 6.0 (no SP) under Linux.
              >>
              >> In fact, I got a Tomcat server (with an application - a servlet -)
              >on my
              >> LAN, which calls my application under my Weblogic server (a servlet
              >calling
              >> some EJBs...)
              >> No problem at the first connection, then the second fails with this
              >> exception :
              >>
              >> I don't know what happens between tomcat and weblogic but what I traced
              >is
              >> that :
              >> 1) Tomcat creates a socket connection with Weblo
              >> 2) Weblo listens to Tomcat for an InputStream
              >> 3) Tomcat sends data via an OutputStream
              >> 4) Weblo receives nothing !!!! <---- problem ? :)
              >>
              >> Here is my exception...
              >>
              >>
              >> <Error> <Posix Performance Pack> <Uncaught
              >> Throwable in processSockets
              >> java.lang.NullPointerException
              >> at weblogic.socket.TunnelContext.getServlet(TunnelContext.java:24)
              >> at
              >>
              >weblogic.servlet.internal.MuxableSocketHTTP.dispatch(MuxableSocketHTTP.java:
              >> 459)
              >> at
              >>
              >weblogic.socket.PosixSocketMuxer.deliverGoodNews(PosixSocketMuxer.java:449)
              >> at
              >> weblogic.socket.PosixSocketMuxer.processSockets(PosixSocketMuxer.java:378)
              >> at
              >weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:23)
              >> at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
              >> at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              >> >
              >>
              >>
              >>
              >> "Mark Priest" <[email protected]> a écrit dans le message de
              >news:
              >> [email protected]...
              >> > I am experiencing a periodic error when accessing a Servlet running
              >under
              >> > weblogic 6 sp2 on Windows 2000. Usually the second time my servlet
              >is
              >> > accessed I see the connection error and then periodically after that.
              >> Here
              >> > is the stack trace:
              >> >
              >> > .lang.NullPointerException
              >> > at weblogic.socket.TunnelContext.getServlet(TunnelContext.java:24)
              >> > at
              >> >
              >>
              >weblogic.servlet.internal.MuxableSocketHTTP.dispatch(MuxableSocketHTTP.java:
              >> > 465)
              >> > at weblogic.socket.NTSocketMuxer.processSockets(NTSocketMuxer.java:638)
              >> > at
              >> weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:23)
              >> > at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
              >> > at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              >> > >
              >> > <Oct 1, 2001 9:38:01 PM EDT> <Error> <HTTP> <Connection failure
              >> > java.lang.NullPointerException
              >> > at weblogic.socket.TunnelContext.getServlet(TunnelContext.java:24)
              >> > at
              >> >
              >>
              >weblogic.servlet.internal.MuxableSocketHTTP.dispatch(MuxableSocketHTTP.java:
              >> > 465)
              >> > at weblogic.socket.NTSocketMuxer.processSockets(NTSocketMuxer.java:638)
              >> > at
              >> weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:23)
              >> > at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
              >> > at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              >> >
              >> > I traced this in the debugger and found that the first error occurs
              >before
              >> > my servlet is even invoked. The second error occurs after I try
              >to read
              >> > from the ServletInputStream object. When the error occurs I must
              >kill
              >the
              >> > client request, which hangs, and then subsequent requests are fine.
              >> >
              >> > I have not seen anything like this in these newsgroups. Does anyone
              >have
              >> > any ideas as to why this is happening?
              >> >
              >> > Thanks,
              >> > Mark
              >> >
              >> >
              >> >
              >> >
              >> >
              >>
              >>
              >
              >
              

  • Socket connect slow in JDK 1.5?

    We recently began testing our Java Swing application with JDK 1.5, and we noticed that socket.connect()
    calls are taking several seconds to return, when before in 1.4 the calls returned immediately.
    Here is some sample code:
    Socket sock = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(inAddress, portNum);
    sock.connect(sockAddr, 2000);
    What could be wrong? I've debugged the code and verified inAddress is an IP address,
    not a hostname.
    -Eric

    Here is the list of enhancements in JDK1.5.
    http://java.sun.com/j2se/1.5.0/docs/guide/net/enhancements-1.5.0.html
    I wonder if any of them are having some effect in the slow connection.
    There are some network properties that you can tweak with. Did you try them?
    Here is the list
    http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html

  • Is there any way to identify the particular socket connection is closed ?

    Is there any way to identify the particular socket connection is closed or not ?
    Any methods ???
    How can the program knows the connection is lost or some thing ...
    Is the socket throws some excpetions when there is no active connection ???
    namanc

    If you get an IOException when you try to use the socket, the connection was obviously closed.
    The correct way for an application to know if the socket was closed is:
    1) the server sends a message indicating that the socket should be closed
    2) the client closes the socket itself

  • I suppose it is the problem with socket connection,Please help

    Hi,
    I'm trying to build a chat server in Java on Linux OS.I've created basically 2 classes in the client program.The first one shows the login window.When we enter the Login ID & password & click on the ok button,the data is sent to the server for verification.If the login is true,the second class is invoked,which displays the messenger window.This class again access the server
    for collecting the IDs of the online persons.But this statement which reads from the server causes an exception in the program.If we invoke the second class independently(ie not from 1st class) then there is no problem & the required data is read from the server.Can anyone please help me in getting this program right.I'm working on a p4 machine with JDK1.4.
    The Exceptions caused are given below
    java.net.SocketException: Connection reset by peer: Connection reset by peer
    at java.net.SocketInputStream.SocketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:119)
         at java.io.InputStreamReader$CharsetFiller.readBytes(InputStreanReader.java :339)
         at java.io.InputStreamReader$CharsetFiller.fill(InputStreamReader.java:374)
         at java.io.InputStreamReader.read(InputStreamReader.java:511)
         at java.io.BufferedReader.fill(BufferedReader.java:139)
         at java.io.BufferedReader.readLine(BufferedReader.java:299)
         at java.io.BufferedReader.readLine(BufferedReader.java:362)
         at Login.LoginData(Login.java:330)
         at Login.test(Login.java:155)
         at Login$Buttonhandler.actionPerformed(Login.java:138)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1722)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:17775)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:4141)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:253)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:261)
         at java.awt.Component.processMouseEvent(Component.java:4906)
         at java.awt.Component.processEvent(component.java:4732)
         at java.awt.Container.processEvent(Container.java:1337)
         at java.awt.component.dispatchEventImpl(Component.java:3476)
         at java.awt.Container.dispatchEventImpl(Container.java:1399)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3302)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3014)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2967)
         at java.awt.Container.dispatchEventImpl(Container.java:1373)
         at java.awt.window.dispatchEventImpl(Window.java:1459)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:439)
         at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
         My program looks somewhat like this :
    1st class definition:
    public class Login extends Jframe// Login is the name of the first class;
    Socket connection;
    DataOutputStream outStream;
    BufferedReader inStream;
    Frame is set up here
    public class Buttonhandler implements ActionListener
    public void actionPerformed(ActionEvent e) {
    String comm = e.getActionCommand();
    if(comm.equals("ok")) {
    check=LoginCheck(ID,paswd);
    test();
    public void test() //checks whether the login is true
    if(check)
    new Messenger(ID);// the second class is invoked
    public boolean LoginCheck(String user,String passwd)
    //Enter the Server's IP & port below
    String destination="localhost";
    int port=1234;
    try
    connection=new Socket(destination,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStream = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    outStream=new DataOutputStream(connection.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    System.out.println("connected to "+destination+" at port "+port+".");
    BufferedReader keyboardInput=new BufferedReader(new InputStreamReader(System.in));
    String receive=new String();
    try{
    receive=inStream.readLine();
    }catch(IOException ex){ error("Error reading from server");}
    if(receive.equals("Logintrue"))
    check=true;
    else
    check=false;
    try{
    inStream.close();
    outStream.close();
    connection.close();
    }catch (IOException ex){
    error("IO error closing socket");
    return(check);
    // second class is defined below
    public class Messenger
    Socket connect;
    DataOutputStream outStr;
    BufferedReader inStr;
    public static void main(String args[])
    { Messenger mes = new Messenger(args[0]);}
    Messenger(String strg)
    CreateWindow();
    setupEvents();
    LoginData(strg);
    fram.show();
    void setupEvents()
    fram.addWindowListener(new WindowHandler());
    login.addActionListener(new MenuItemHandler());
    quit.addActionListener(new MenuItemHandler());
    button.addActionListener(new Buttonhandle());
    public void LoginData(String name)
    //Enter the Server's IP & port below
    String dest="localhost";
    int port=1234;
    int r=0;
    String str[]=new String[40];
    try
    connect=new Socket(dest,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStr = new BufferedReader(new InputStreamReader(connect.getInputStream()));
    outStr=new DataOutputStream(connect.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    String codeln=new String("\n");
    try{
    outStr.flush();
    outStr.writeBytes("!@*&!@#$%^");//code for sending logged in users
    outStr.writeBytes(codeln);
    outStr.write(13);
    outStr.flush();
    String check="qkpltx";
    String receive=new String();
    try{
    while((receive=inStr.readLine())!=null) //the statement that causes the exception
    if(receive.equals(check))
    break;
    else
         str[r]=receive;
         r++;
    }catch(IOException ex){ex.printStackTrace();error("Error reading from socket");}
    catch(NullPointerException ex){ex.printStackTrace();}
    } catch (IOException ex){ex.printStackTrace();
    error("Error reading from keyboard or socket ");
    try{
    inStr.close();
    outStr.close();
    connect.close();
    }catch (IOException ex){
    error("IO error closing socket");
    for(int l=0,k=1;l<r;l=l+2,k++)
    if(!(str[l].equals(name)))
    stud[k]=" "+str[l];
    else
    k--;
    public class Buttonhandle implements ActionListener
    public void actionPerformed(ActionEvent e) {
    //chat with the selected user;
    public class MenuItemHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    String cmd=e.getActionCommand();
    if(cmd.equals("Disconnect"))
    //Disconnect from the server
    else if(cmd.equals("Change User"))
         //Disconnect from the server & call the login window
    else if(cmd.equals("View Connection Details"))
    //show connection details;
    public class WindowHandler extends WindowAdapter
    public void windowClosing(WindowEvent e){
    //Disconnect from server & then exit;
    System.exit(0);}
    I�ll be very thankful if anyone corrects the mistake for me.Please help.

    You're connecting to the server twice. After you've successfully logged in, pass the Socket to the Messenger class.
    public class Messenger {
        Socket connect;
        public static void main(String args[]) {
            Messenger mes = new Messenger(args[0]);
        Messenger(Socket s, String strg) {
            this.connect = s;
            CreateWindow();
            setupEvents();
            LoginData(strg);
            fram.show();
    }

  • Problem with socket connection

    have my gps reciver connected to the usb port - i have a daemon gpsd running which makes data available on tcp port 2947 for querying. when i do telnet, it gives proper data.
    but when i open a socket connection using java, it does not print anything as output. actually telnet asks for an escape charatcer so i am sending "r" initially to the server but still the program does not print anything as output.
    here is my java code -
    import java.io.*;
    import java.net.Socket;
    public class test2
    public static void main(String[] args)
    try
    Socket s = new Socket("localhost",2947);
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
    s.getOutputStream())),true);
    out.println("r");
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String line;
    while(true)
    line = in.readLine();
    System.out.println(line);
    catch (Exception e)
    or sometimes it even shows error as
    Exception in thread "main" java.net.SocketException: Invalid argument or cannot assign requested address
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    and this is the output which i get on telnet -
    ot@localhost ~]# telnet localhost 2947
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    r
    GPSD,R=1
    $GPRMC,000212,V,18000.0000,N,00000.0000,W,0.0000,180.000,101102,,*1A
    $GPGSA,A,1,,,,,,,,,,,,,,,,*32
    $PGRME,400.00,0.00,0.00*7B
    $GPRMC,000213,V,18000.0000,N,00000.0000,W,0.0000,180.000,101102,,*1B
    $GPGSA,A,1,,,,,,,,,,,,,,,,*32
    $PGRME,400.00,0.00,0.00*7B
    $GPRMC,000214,V,18000.0000,N,00000.0000,W,0.0000,180.000,101102,,*1C
    $GPGSA,A,1,,,,,,,,,,,,,,,,*32

    Actually the problem does not seem to be in the code because i tried some basic client server programs (without any gpsd etc in picture) and even they are not working in linux though they work perfectly in windows (on the same machine). In linux it shows exception
    My socket programs dont work in linux it shows error -
    ot@localhost winc]# java parser
    Exception in thread "main" java.net.SocketException: Invalid argument or cannot assign requested address
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
    at java.net.Socket.connect(Socket.java:452)
    at java.net.Socket.connect(Socket.java:402)
    at java.net.Socket.<init>(Socket.java:309)
    at java.net.Socket.<init>(Socket.java:124)
    at parser.main(parser.java:10)
    i have removed the firewall settings etc and it still doesnot work in linux
    what could be the cause for this?
    Sowmya

  • Problem with socket connection through Java Embedding...

    We are trying to create a simple socket connection to a socket server through BPEL PM using the Java Embedding component.
    BPEL Process : Client makes an asynchronous request. Passes an input variable. The input variable is sent to the Server Program through a socket connection through the Java embedding component.
    Server: We are running a simple Socket Server program from command prompt.
    The code below works fine as long as we do not try to receive a response from the server (Commented Code).
    If we uncomment the code and try to receive a response, it refuses to create an instance for the BPEL Process. And sometimes restarts the BPEL Server.
    Client Code:
    String msg="NONE";
    try{
    org.w3c.dom.Element input = (org.w3c.dom.Element) getVariableData("inputVariable","payload","/client:clientProcessRequest/client:input");
    msg = input.getNodeValue();
    Socket clientsoc=new Socket("ServerIP",1000);
    PrintWriter out1=new PrintWriter(clientsoc.getOutputStream());
    out1.write(msg);
    out1.flush();
    BufferedReader cin1=new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));
    msg=cin1.readLine();
    setVariableData("outputVariable","payload","/client:result",new String(msg));
    clientsoc.close();
    catch(UnknownHostException e)
    System.err.println("Don't know about host: dev.");
    System.exit(1);
    catch (IOException e)
    System.err.println("Couldn't get I/O for "+ "the connection to: dev.");
    System.exit(1);
    }

    Repost

  • Problem with socket connection in midp 2.0

    hello everyone.
    I'm new one in j2me and I am learning socket connection in j2me. I'm using basic socket,datagram example wich is come with sun java wireless toolkit 2.5. for it i wrote small socket server program on c# and tested it example on my pc and its working fine. also socket server from another computer via internet working fine. But when i instal this socket example into my phone on nokia n78 (Also on nokia 5800) it's not working didn't connect to socket server.. On phone I'm using wi-fi internet. Can anybody help me with this problem? I hear it's need to modify manifest file and set appreciate pressions like this
    MIDlet-Permissions: javax.microedition.io.Connector.socket,javax.microedition.io.Connector.file.write,javax.microedition.io.Connector.ssl,javax.microedition.io.Connector.file.read,javax.microedition.io.Connector.http,javax.microedition.io.Connector.https
    is it true?
    can anybody suggest me how can i solve this problem?
    where can I read full information about socket connection specifiecs in j2me?
    Thanks.

    Maybe this can be helpful:
    [http://download-llnw.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/index.html]
    you can check there the Datagram interface anda DatagramConnection interface and learn a little about that.
    If the client example runs fine in the wireless toolkit emulator, it should run the same way in your phone; i suggest to try to catch some exception that maybe is hapenning and display it on a Alert screen, this in the phone.

  • How to make a socket connection timeout infinity in Servlet doPost method.

    I want to redirect my System.out to a file on a remote server (running Apache Web Server and Apache Tomcat). For which I have created a file upload servlet.
    The connection is established only once with the servlet and the System.out is redirected to it. Everything goes fine if i keep sending data every 10 second.
    But it is required that the data can be sent to the servlet even after 1 or 2 days. The connection should remain open. I am getting java.net.SocketTimeoutException: Read timed out Exception as the socket timeout occurs.
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.
    Following is the coding to establish a connection with the Servlet.
    URL servletURL = new URL(mURL.getProtocol(), mURL.getHost(), port, getFileUploadServletName() );
    URLConnection mCon = servletURL.openConnection();
    mCon.setDoInput(true);
    mCon.setDoOutput(true);
    mCon.setUseCaches(false);
    mCon.setRequestProperty("Content-Type", "multipart/form-data");
    In the Servlet Code I am just trying to read the input from the in that is the input stream.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    byte [] content = new byte[1024];
    do
    read = in.read(content, 0, content.length);
    if (read > 0)
    out.write(content, 0, read);
    I have redirected the System.out to the required position.
    System.setOut(........);
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.

    I am aware of the setKeepAlive() method, but this can only used with the sockets. Here i am inside a servlet, have access to HTTPServletRequest and HTTPServletResponse and I don't know how to get access to the underlying sockets as the socket handling will be handled by the tomcat itself. If I am right there will be method in the apache tomcat 6.0.x to set this property. But till now I am not getting it.

  • Multiple clients on socket connection

    Hi!
    I understand that it is possible that multiple clients listen to one server (on the same port) and even write to it (then it should be a multi-threaded server).
    But i would like to refuse connectios, if one client is connected. How can I do that?
    In my case I have a (single threaded) server. Now one clients connects. The server waits to receive data from the client and answers, without ever closing the port. that works.
    Now if I connect with a second client, the openicng of the socket in the second client works fine, although the server does not seem to notice the second client. Communication is not possible between the server and the second client, and the server doesn't answer to the first client anymore, although he receives data from it.
    So, since the server does not seem to notice the second client (does not accept the connection) and I don't get an exception at the second client, what can I do?
    Thank you for your help!
    concerned Code (if you want to take a look at it):
    CLIENT:
    socket = new Socket(hostname, echo_port);
    SERVER:
    try
    ServerSocket waitingsocket = new ServerSocket(echo_port);
    try
         socket= waitingsocket.accept();
         System.out.println("Client connected");
         ReaderThread reader = new ReaderThread( this, socket );
         reader.start();          
    catch (Exception e)
    READER:
    public void run()
         while (true)
              try {
                   int bytesRead = inStream.read(inputBuffer,
                   0, inputBuffer.length);
                   readCallback.tcpUpdate(inputBuffer,bytesRead);
              catch (Exception oops)
                   readCallback.tcpUpdate(null,-1);
              

    Just to make sure this is clear: You can NOT have multiple clients on a given socket connection. You CAN have multiple clients connected to a particular port on a given server, but each client will be communicating with the server through a different of socket.
    The usual approach here is to set up a listening ServerSocket on the desired port, call accept() on it, then process the communication from the returned Socket object. This is usually done by spawning a new thread and allowing it to handle the socket communication, while the ServerSocket loops around to another accept() for the next communication.
    Here's an excellent intro to the concepts (the code is really ugly and poorly implemented, but it does a good job of explaining the overall concept). I used this as a starting point, and now (after a whole lot of development) have a pretty sweet extensible web server class that handles template expansion, etc... (I use this as a quick and dirty UI for some of my apps, instead of requiring the user to install a JSP container):
    http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/
    - K

  • How can i reuse my existing socket connection

    Hi,
    this might sound basic, it probably is:
    As part of my larger project, i have to send and recieve data to multiple socket connections.
    The thing that happens is that everytime i send data, it seems that java is creating a new stream or something (code is multithreaded)
    so as i send 4 items of data, a bit like a chat program sending 4 statements, it creates 4 different streams, instead of using the same stream. therefore when i close the connection, i get:
    java.net.SocketException: Connection reset 4 times.
    i know why.. its because i have added the:
    Socket socket=new Socket(host, port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    bit in the same method with the
    out.println(THE DATA....);
    out.flush();
    The thing what i want to do is to create the connection one, and reuse the objects:
    out, in and socket
    to send / recieve the new data.
    please help me guys,
    thanks

    All the threads would be able to get the same reference to....
    class SocketWrapper {
         private final Object readLock = new Object();
         private final Object writeLock = new Object();
         // client side
        public SocketWrapper(String hostname, int port);
         // server side.
        public SocketWrapper(Socket);
         // send data
         public void send(Serializable object) throws IOException;
         // receive data. synchronized(writeLock);
         public Serializable getNext() throws IOException;
         // create a new socket as required, throw IllegalState if server side. synchronized(readLock)
         private void createNewSocket() throws IllegalStateException;
    }The send autoconnects as required. It then send on message/packet/object.
    The getNext autoconnects as required. It reads one message/packet/object and returns.
    This allows multiple threads to access the same socket. It allows data to be sent while a thread is blocking on a read. (Thus two locks)

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

Maybe you are looking for

  • How to use standard texts in smartforms

    Hi Friends,       How to use standard texts in smartforms, ie in scripts we are using standard texts using tr so10. thanks in advance, regards, sharma.

  • XML transformation encoding

    Hi all! I'm using a SIMPLE TRANSFORMATION to generate an XML file that is sent to a legacy system. After the CALL TRANSFORMATION statement, I get the XML string, but it starts with: <?xml version="1.0" encoding="utf-16"?> My legacy system can read on

  • Deleting files stored in Playbook Bridge Files

    Does anyone know how to delete files that have been saved in Bridge Files?

  • G5 + 1080p LCD

    Hey fellas, I just upgrade my TV from a 720p sharp to a 1080p panasonic. I used an hdmi cable before with no problems. when I hooked up my panasonic, the native resolution was not working properly and the image was flickering on and off and the color

  • How do I delete the "other" memory from my Iphone 4?

    Most of the memory on my phone is taken by music, but the "other" memory is getting annoying. It takes up 1.34GB and i want to delete it. can anyone help me?