ServerSocket

Hi,
I wanted to use my Android as a Server and hence was trying to create a serversocket using the following lines of code.
It works when I simulate a run on my desktop however when I deploy it on my Mobile it throws the error
Error: Error #2002: Operation attempted on invalid socket
Actually its unable to bind this socket to the address I provided.
Code:
var server:ServerSocket = new ServerSocket();
server.addEventListener(Event.CONNECT,onConnect);
server.bind(1234,"127.0.0.1");
server.listen();
I tried creating a server socket thereafter using the java code ,it worked but what I really want is to connect my clients to serversocket based out on Flex.
Let me know If you have any suggestions/workaround

See this networking tutorial
http://java.sun.com/docs/books/tutorial/networking/index.html

Similar Messages

  • After closing serversocket, process remains

    Hi everyone,
    I'm trying to learn to write a client/server program. I begin by creating a serversocket and waiting for data. When I close the program, the serversocket still remains even when I create handlers that try to close the socket after the GUI has been closed.
    The server is as follows:
    try
                   ServerSocket myServerSocket = new ServerSocket(6666);
                   myServerSocket.setReuseAddress(true);
                   writeToDebugger("Server successfully created.  Listening on port 6666\n");
                   //     open a socket for listening for multiple requests
                   while(listening)
                             clientSocket = myServerSocket.accept();
                             //clientSocket.setReuseAddress(true);
                             writeToDebugger("Client " + clientSocket.getInetAddress().toString() + " accepted.");
                             //store clientSocket information
                             out = new PrintWriter(
                                    clientSocket.getOutputStream(), true);
                             in = new BufferedReader(
                                      new InputStreamReader(
                                          clientSocket.getInputStream()));
                             while ((inputLine = in.readLine()) != null && inputLine != "")
                                  writeToDebugger(inputLine);
                             //breaker = inputLine.indexOf(',');
                             //store the incoming request's information --- username of requestor is first param, requested username is second param
                             //database.put(inputLine.substring(0, breaker), clientSocket.getInetAddress());
                             //return the IP address of the username lookup
                             //out.print(database.get(inputLine.substring(breaker+1)));     
              }Here is my closing handler:
    public void windowClosed(WindowEvent arg0) {
              listening=false;
              try
                   System.out.println("CLOSING FOR REAL");
                   if(clientSocket!=null)
                        clientSocket.close();
                        clientSocket.shutdownInput();
                        clientSocket.shutdownOutput();
                   if(myServerSocket!=null)
                        myServerSocket.close();
                   if(out!=null)
                        out.flush();
                        out.close();
                   if(in!=null)
                        in.close();
                   System.out.println("DONE CLOSING");
              catch(Exception e)
                   System.out.println(e.getMessage());
         }If someone could please tell me why I have to go into the task manager to close the process after I have already closed the GUI, I'd really appreciate it.
    Thanks in advance,
    Julian

    And you're doing all these closes in the wrong order, and redundantly.
    Just close 'out' and the ServerSocket, doesn't matter in what order here.
    All the other closes and shutdowns are redundant. Calling shutdownXXX after closing the socket does nothing (and calling them just before closing the socket would add nothing to what close() already does). Closing the client socket before closing the output stream built around the socket output stream denies the output stream the chance to flush.

  • Two servers (serverSocket) behind the SAME firewal !?l

    Hello !
    I dont know if this is the right forum for this qusetion,
    and maybe the question is really stupid, but ...
    I made a little client/server application, just to
    play around with sockets and serverSockets.
    It works fine, but now i ask myself:
    What happens, if there are two of my servers running on two
    different computers in the SAME LAN behind the SAME
    firewall/internetgateway, and both are listening on the SAME
    port ?
    F.e. if the extern IP of this LAN/(its gateway) is
    204.556.234.123, and a client in the internet is connecting
    to it on the port, on which the two servers behind the firewall
    are listening, WHO'S ANSWERING ?
    (If this port is set to "open and forward" in the firewall)
    The one with the shorter patch-cable ? ;)
    How is it possible for the client to differenciate
    this two servers in that LAN?
    The only logical solution i found is that this two servers
    have to listen on different ports,
    but i think there has to be another explanation and/or solution.
    Do i have to take care about situations like that in my
    server-application ?
    I have the feeling that i have to...somehow.
    OK, you see i dont know much about this...
    i would be very thankful for every hint and explanation.
    Thank you very much,
    greetings,
    huni.

    F.e. if the extern IP of this LAN/(its gateway) is
    204.556.234.123, and a client in the internet is
    connecting
    to it on the port, on which the two servers behind the
    firewall
    are listening, WHO'S ANSWERING ?
    (If this port is set to "open and forward" in the
    firewall)Whichever one the firewall is told to forward it to!
    The two computers running your server have unique addresses on the internal network. The firewall will forward incoming connections to one of those addresses. Maybe it can do some simple "load balancing" by forwarding some connections to one server and some to the other, but still, any particular connection will only go to one server.

  • How can I connect to a ServerSocket behind proxy ???

    Hi,
    I have been searching for this answer for a very long time. My question is simple:
    Let's say I have an Instant Messenger application written in Java. I will call it JICQ.
    If my JICQ is installed in a machine with invalid IP address (192.168.1.100) behind a proxy server (Wingate), how in the heck another JICQ outside my intranet can send me a point-to-point message ????
    How can an application from outside my Intranet get to my ServerSocket running on my machine with a invalid IP address and behind a proxy server ???
    I think ICQ does just that, and I am very curious in knowing how it does that.
    I will explain better the ICQ cenario:
    I am behind a proxy server (Wingate) and my machine has an invalid IP address (192.168.1.100).
    I have ICQ running on that machine.
    How can other people connect to my ICQ to send me instant messages and files ???
    Is it a point-to-point connection ??? (I think so)
    [ICQ] -------> [PROXY] --------> [My ICQ]
    I would be very thankful if someone can explain me that.
    []'s
    Sergio Oliveira Jr.

    Tony, could you please explain me better the procedure that you wrote?
    What are the boxes? My situation is similar:
    | ServerSocket (1) |
    | (192.168.1.100, 5555) |
    |
    |
    |
    |
    | Proxy |
    | Someone wants to connect to the ServerSocket (1) |
    That is not true. You CAN do it but you need a box
    outside the firewall with proper IP address to help
    you. I am not sure if Sergio still wants the answer
    today after more than a year from the original post (I
    did not see the post until today when I try to search
    for something else). Anyway, if such a box is
    available (I call it 2nd box), you could first
    establish a socket between the two boxes by HTTP
    tunneling (I assume it is a http proxy). You have to
    initiate the socket from the 1st box. Then start
    another server socket on the 2nd box, forwarding the
    traffic it gets from outside back to the 1st box using
    the established channel. That is it.
    Tony

  • How to get  ServerSocket to tell client that it's not accepting?

    I've had a couple of other topics recently, concerning my attempt to write a client/server TicTacToe game for my final project in Data Comm. I've got almost all of what I want worked out this week, but I'm stumped on this one. The project spec includes some way of controlling access to the application on the server -- do some work on figuring out the limits of the resources, and set up a way to limit the number of clients that can connect at one time.
    I thought that for my purposes, for proof of concept, I would set it up so that up to 3 clients could play at one time, and up to 2 could be allowed to "connect, but wait for a turn" until someone playing logged off. Conceptually I can draw a flow chart of it, but what I can't figure is this -- I have a server object that accepts connections with ServerSocket.accept(), and sends off the socket created as an argument to a new thread of the ServerGame class. ServerGame has a static int for threadcount. I can code in ServerGame to limit it to 3 who can actively be allowed to play, and send a message back to someone who connects later to say, "Wait", and in the Server itself I can refuse to accept() if a 6th client tries to connect, but for that 6th client -- how can I get a message saying "You can't even connect now -- no room even in the queue"? If the server doesn't even accept(), what's the means of response, other than the poor client sitting there with an unresponsive button in his GUI? That's what happens now -- the first client that tries to connect when the server won't accept, his GUI just freezes. Not a good interface.
    Unfortunately this is a Data Comm class, and the teacher is new this year and comes from 25 years in industry and knows C/C++, but no java.

    My puzzlement is that I'm a beginner ( we just got introduced to the idea of sockets in class a month ago, and I chose java not only because I like it best but golly, the socket API in C and C++ is awful compared to java).
    My understanding of ServerSocket is that it does not make a connection that it can use itself, but passes off to something or someone. My model is to have a ServerGame class, threaded so the Server spawns a new thread of ServerGame for each new socket and passes the socket to the constructor of the new ServerGame thread. The it goes off and does its thing.
    So I don't understand what you mean by setting a flag (I understand flags, just not what the idea is in this case). And how can I call a function on a server on a different machine? Chicken and egg -- how can I communicate if I can't connect, and if I do connect the connection is sent off to the ServerGame, not the Server itself.
    Wait -- just thought of something -- is this what you mean? If I set a condition that recognizes I've reached the limit, ServerSocket could create a connection but NOT send it to the ServerGame, but to a temporary object of some kind, that just sends back a message and closes and dies?
    Sounds do-able, but time's up, I gotta get to school. I'll check in later
    Thanks a lot
    F

  • ServerSocket bind, bug or windows feature

    I wanted to check if a TCP socket was already bound before attempting to use it.
    I had my own ideas, but looked for other ideas as well.
    While testing these other ideas I stumbled on the following issue.
    On Windows XP(SP3), its the work platform of choice, I noted the following from a netstat:
    $ netstat -an|grep 139
    TCP 10.11.13.98:139 0.0.0.0:0 LISTENING
    TCP 192.168.56.1:139 0.0.0.0:0 LISTENING
    TCP 192.168.113.1:139 0.0.0.0:0 LISTENING
    TCP 192.168.231.1:139 0.0.0.0:0 LISTENING
    Note that this is the Windows 'NETBIOS Session Service' of course and that it is bound to all my machines interfaces except for the loopback.
    If I execute the following call:
    ServerSocket anyAddressSocket = new ServerSocket(139, 2, null);
    I will not get java.net.BindException thrown.
    I will see a new listener bound to port 139 and the 'any address' as follows:
    $ netstat -an|grep TCP|grep 139
    TCP 0.0.0.0:139 0.0.0.0:0 LISTENING
    TCP 10.11.13.98:139 0.0.0.0:0 LISTENING
    TCP 192.168.56.1:139 0.0.0.0:0 LISTENING
    TCP 192.168.113.1:139 0.0.0.0:0 LISTENING
    TCP 192.168.231.1:139 0.0.0.0:0 LISTENING
    But if I replicate the situation using Java on a different arbitrary port as follows:
    List<ServerSocket> sockets = new ArrayList<ServerSocket>();
    Enumeration<NetworkInterface> enumOfNetworkInterfaces =
    NetworkInterface.getNetworkInterfaces();
    while(enumOfNetworkInterfaces.hasMoreElements())
    NetworkInterface networkInterface = enumOfNetworkInterfaces.nextElement();
    List<InterfaceAddress> addrs = networkInterface.getInterfaceAddresses();
    for(int idx = 0; idx < addrs.size(); idx++)
    InterfaceAddress intFace = addrs.get(idx);
    if (!networkInterface.isLoopback())
    ServerSocket socket = new ServerSocket(7777, 2, intFace.getAddress());
    sockets.add(socket);
    // At this point, netstat shows the same output as the first port 139 output above.
    ServerSocket brokenSocketNo = new ServerSocket(7777, 2, null);
    I will get the expected exception:
    "java.net.BindException: Address already in use: JVM_Bind"
    I am testing this with Java 6u6 which I know is old, but is what is required to be used for this product.
    Is this a bug in the JVM implementation? I cannot find any reference to such in the bugs DB.
    Is this a feature of Windows TCP stack?
    I have not tried this on a linux platform because I am really trying to understand the issue as exhibited on the MS platform.
    Any insight into this would be helpful.
    Cheers Mark

    Hello EJP.
    Thanks for that pointer.
    I tried it as you indicated and inside the loop using the following:
    ServerSocket socket = new ServerSocket();
    socket.setReuseAddress(true);
    socket.bind(new InetSocketAddress(intFace.getAddress(), 7777), 2);
    Each ServerSocket is now listening on a specific interface using the 'setReuseAddress(true);' call.
    This by itself did not change the effect I see when I then make the call 'new ServerSocket(7777, 2, null)' which succeeded with port 139 but not with my port 7777 test.
    If I changed the call for the for the 'wild card' address to also use 'setReuseAddress(true);' then all succeeds, but this is not the situation that succeeded with the port 139 test.
    I think I am still attempting to solve the issue as a bug or a 'windows XP feature', but I am leaning more about the intricacies of sockets.
    I will follow your suggestion and have a look at 'Stevens' 3rd Edition.
    Cheers Mark

  • Can I check remote address connecting to a ServerSocket before accepting?

    I have a ServerSocket for which I'd like to implement an IP filter, using an allow or deny list to control which IP addresses can connect. After accepting the connection, I check the remote address on the Socket that is created, and apply the filter. However, if I close the connection to a denied address, the client sees that the connection was accpeted, but then it throws a SocketException when it tries to write to it.
    That accomplishes the purpose of the filter, but it doesn't seem like good behavior from the client's perspective. I'd like to implement a ServerSocket that doesn't even accept the connection if the remote address is not permitted. Is there any way to do that?

    Why not write a connection accepted/refused message
    to the client and then carry on (or close the
    socket/streams at both ends)?I'm not sure I understand your suggestion. When ServerSocket.accept() returns by providing a Socket object, that is the first time the server code can determine the IP address of the client and apply an IP filter. However, the connection has already been established at this point, so it's not possible to make an accept/refuse decision for the connection based on the client IP address. By the time the server code sees the IP address, the connection has already been accepted, and the only recourse is to close the connection from the server (by calling close() on the Socket object that was returned), and the client will then throw an exception with the message saying that the software closed the connection.
    Legitimate users trying to connect may interpret this as a software problem, if they don't know any better. Intruders will discover from this behavior that the port is open through the firewall, and may conclude that IP filtering is being applied, and if they have some idea of what IP addresses are allowed, they could easily spoof them. Or they could keep trying, hoping to catch the server when the IP filtering is turned off.
    It would be better to mimic the filtering behavior of a firewall, whereby the connection is not established. Then the client would report that it could not establish the connection, and the user would be more likely to look into whether the port is open or IP filtering is occurring, rather than thinking there is a software problem. And the intruder would conclude that the port is not open and go somewhere else.
    I would need a different implementation of ServerSocket to do this. I checked jakarta commons net, but that only provides client side utilities. I'm currently untangling the source code of java.net.ServerSocket to see how difficult it will be to override the accept() method to provide filtering behavior. This seems like a useful thing, and I thought perhaps someone had already done so. Or perhaps someone can tell me why this is not a good idea.
    Message was edited by:
    MidnightJava

  • Cannot Stop Thread with ServerSocket

    Hi
    I have a problem with a Thread that runs a ServerSocket. I want to stop this Thread from the main-application:
    Thread class:
    Constructor:
    serverSocket = new ServerSocket(address, port);
    public void run() {...
    while (true) { ....
    clientSocket = serverSocket.accept();
    I want to do the following in the main-application:
    because I want to set up a Thread with a new ServerSocket:
    myThread = null; // to stop the Thread, I also have tried to interrupt without success
    myThread = new Thread(); // => BindException and serverSocket == null;
    I always catch a BindException and in the Thread-Constructor the serverSocket is set null !
    How can I avoid this?
    I need to get a new serverSocket!!
    Can anyone help me?
    thanks, walter

    Thank's for reply: The problem I have is the following: My domain has a dynamic IP, so after the IP changes the s.accept() does not work any more!
    try // Point 1 *)
    ServerSocket s = new ServerSocket(portNumber);
    for(;;)     
    Socket incoming = s.accept(); // does not work after IP changes
    new ThreadedEchoHandler(incoming, i).start();
    So I have to detect that the IP has changed and have to start again at Point 1
    How can I do this?
    thx walter

  • J2ME serversocket on Siemens S55?

    I try to establish a serversocket connection on a Siemens S55 device. My aim ist to realize a webserver application on the mobile phone. I want the S55 to act as a server, accepting client connections from other devices / pc's.
    The J2ME MIDlet works fine on the SMTK S55 emulator. But when I start the midlet I always get an IOException from the acceptAndOpen()- method.
    Here's the source code:
    String url = "serversocket://:" + port;
    try {
    notifier = (StreamConnectionNotifier) Connector.open(url);
    sConnection = notifier.acceptAndOpen();
    catch(IOException e) {
    display.appendText(e.toString() );
    Does anyone have any experience with this problem?

    I have the same problem on a SL45i phone. It seems it has to do with dial up connection.
    I read about this in a document called "SMTK_ProgRefM50.pdf", but it's still quite unclear to me. What I understand of it, is that you can't use a WAP provider for HTTP requests. You would need a 'normal' internet provider (like when you dial-up with an analog modem in a computer). The problem is that, although all settings seem to be correct, I can't connect to such a provider.

  • ConnectionReset on serverSocket

    Hi, i have a problem with my java ftp server..
    my server is active 24h/24 but "Sometimes" if i try to connect i receive reply "Connection reset"
    the server locked and i must restart the application, but this is a problem !!
    this is my code for run
    public void run(){
        Socket socket;
        // IMPOSTO INDIRIZZO IP DI DEFAULT
        String indirizzoIP = "";
        try{
          // LETTURA DA FILE DI CONFIGURAZIONE DELL'INDIRIZZO IP (se vuoto utilizzo quello locale)
          indirizzoIP = Conf.getNodeValue("Server.ip");
          if (indirizzoIP.equals("")){
               indirizzoIP = java.net.InetAddress.getLocalHost().getHostAddress();
          ss = new ServerSocket(Conf.getServerPort(),100, InetAddress.getByName(indirizzoIP));
          obsServerStarted(true);
          while(true){ 
                try { Thread.currentThread().sleep(1000); } catch (Exception ex) {}
                          socket = ss.accept();
                        if (!Conf.isBanned(socket) && probes.size() < maxConnections) {
                             // CONTROLLO LIMITE SESSIONE
                             if (sessionNr >= Integer.MAX_VALUE){
                                  sessionNr = 0;
                             // INCREMENTO IL NUMERO DI SESSIONE
                             sessionNr = sessionNr+1;
                             Probe p = new Probe(socket, this, sessionNr);
                           probes.add(p);
                             obsClientConnected(p.ses.us);
                           p.start();
                        }else {
                             socket.close();
        }catch(SocketException se) {
             bb.dockException(se,"");
                   if (!suspended){
                        obsServerStarted(false); //server could not be started
                        // SERVER NON AVVIATO
                        arrestaProgramma(indirizzoIP, Conf.getServerPort() );
        }catch(IOException e){
          bb.dockException(e,"");
         } catch (Exception e) {
              bb.dockException(e,"");
              // SERVER NON AVVIATO
              if(indirizzoIP.equals("")){
                   indirizzoIP = "unknown";
              arrestaProgramma(indirizzoIP, Conf.getServerPort() );
              if(suspended)
                   obsServerStoped();
      }there is errors?
    thanks in advice

    i not understand sorry
    in my exception the function "arrestaProgramma" close the serversocket (in IOException i must add this )
    but for while i not understand.. how do you mean ?
    }catch(SocketException se) {
         bb.dockException(se,"");
         if (!suspended){
              obsServerStarted(false); //server could not be started
                   arrestaProgramma(indirizzoIP, Conf.getServerPort() );
         }catch(IOException e){
              bb.dockException(e,"");
         } catch (Exception e) {
              bb.dockException(e,"");
              // SERVER NON AVVIATO
              if(indirizzoIP.equals("")){
                   indirizzoIP = "unknown";
              arrestaProgramma(indirizzoIP, Conf.getServerPort() );
         }

  • Creating a serverSocket while sonnecting to a socket on the same port

    I want to make a file transfer application for multiple clients, there will not be a server that users will connect to, the application serves as client AND server, every client will have a serversocket object listen for new connections (it will recieve a connection when someone wants to send a file to them) and I will also have a socket object that will connect to a client when I want to send a file to them.
    Is it possible to run all these connections on a single port? Or will there be a conflict?

    836981 wrote:
    I want to make a file transfer application for multiple clients, there will not be a server that users will connect to, the application serves as client AND server, every client will have a serversocket object listen for new connections (it will receive a connection when someone wants to send a file to them)Read up on peer-to-peer.
    and I will also have a socket object that will connect to a client when I want to send a file to them.A new socket for each outbound connection.
    Is it possible to run all these connections on a single port?Yes. A serversocket listens for connections to a specific port number, it can accept many connections.
    Or will there be a conflict?No. Your outbound connections will not use the same port number locally.
    You are more likely to encounter problems with clients (peers) behind NAT routers.

  • Solaris 9 in a Sun Fire V100 Box ServerSocket Bug

    I am running Solaris 9 in a Sun Fire V100
    I am having a problem openning Sockets where programs are written in Java.
    The program is written in Java with the ServerSocket class.
    I wrote a very simple class to test.
    The port is available of course I already verified it.
    I checked with the SecurityManager to verify this is not a
    security policy but I receive a null from the System.getSecurityManager
    which means there is no securityu manager installed.
    I have many other apllications that are able to open ports and listen, but Java seams
    to be having problem in Solaris 9. I have tried 5 different versions of Java. Last version
    I tried is jsdk 1.4.2_05.
    The same thing happens with Tomcat that crashes while
    trying to open a listening Socket.
    ServerSocket server;
    try
    server = new ServerSocket(8005,1024, InetAddress.getByName("127.0.0.1"));
    System.out.println("BINDING SUCCESFUL");
    catch(Exception e)
    System.out.println(e);
    System.exit(-1);
    while(true)
    try
    Socket clientSocket = server.accept();
    ClientHandler2 t = new ClientHandler2(clientSocket);
    t.start();
    catch(IOException e)
    System.err.println( e );
    Is this a well known bug...
    Can anyone be so kind to help me up with this terrible matter
    Thank you,
    Juanpablo Lajud

    Hi,How to set my link up in solaris 10 ?
    I dont know want happend to my machine solaris v440 it suddenly disconnected from n/w and finally i came to know that is a problem with NIC card..i din't find any light's glowing back side of the machine at NIC card.
    can any one help me in this pls how can i proceed furture for getting my NIC back?
    and i have excuted few commands
    #ndd -set /dev/ce instance 0
    #ndd -set /dev/ce adv_1000fdx_cap 1
    #ndd -set /dev/ce adv_autoneg_cap 0
    I have got dladm show-dev is
    ce0 link: unknown speed: 1000 Mbps duplex: full
    ce1 link: unknown speed: 0 Mbps duplex: unknown
    I dont understand that why my link is showing still unknown ...any help..

  • ServerSocket(TCP/IP) listening in the web container part

    So, if I implement the ServerSocket(TCP/IP) listening in the web container part (Websphere), what is the best way to do this?
    I need to monitor socket state and statistics from browser.
    When I receive message from socket, I must read something from database and send as response to client (meaning I need to create my own thread to do this).
    Solution:
    - to have one servlet with serverSoket listener in it or
    - during web application statup to start my own thread with serverSoket listener
    - or....
    Also there is a problem that websphere write warning when i try do use DB connection from thread I have created!
    Any suggestion?

    hi,
    do you use websphere? version?
    More details:
    http://www.javaranch.com/newsletter/200403/AsynchronousProcessingFromServlets.html
    According to a Technical note from WebSphere support "If a Servlet is spinning its own threads and accessing a database, the J2EE specification is not clear on this, so WebSphere Application Server 5.0 will allow it at this time. IBM is working with Sun to clarify this in the specification, so eventually (i.e. J2EE 1.4) spun threads from a Servlet accessing a database outside of a transaction will not be supported either". Later the same tech note states "Customers should consider changing their application to comply with the J2EE specification."
    and check this
    http://www-1.ibm.com/support/docview.wss?uid=swg21121449

  • Bug in the ServerSocket InputStream.read()

    I believe there is a bug in the ServerSocket InputStream.read() method.
    This is demonstrated under Windows XP, running 1.4.0_01-b03
    I am looking for confirmation and an examination of my assumptions for this.
    There is nothing that suggests the InputStream.read() method should block on a EOL, yet it does.
    This is demonstrated with the following code.
    To reproduce uncomment one of the 'Case' sections in the MyServer code. Compile both classes. Run the MyServer then MyClient code.
    The expected result for ALL cases should be
    ***socket start
    text1
    text2
    But for the first case the last line is not printed. Note that for case 3 it does work, and the only exception is that available() is called.
    The InputStream of the server resolves to java.net.SocketInputStream. The read() method calls the read(byte, int, int) method (which how I guessed that calling available would produce different results.)
    //-----------------Client
        import java.io.*;
        import java.net.*;
        public class MyClient
            private MyClient() {}
            static public void main(String argv[])
                try
                    Socket s = new Socket("127.0.0.1", 50080);
                    OutputStream os = s.getOutputStream();
                    String text = "text1\r\ntext2";
                    os.write(text.getBytes());
                    os.flush();  // We know it was sent.
                    // Important!  The socket remains open!
                    while(true)
                        Thread.currentThread().sleep(60 * 1000);
                catch(Throwable e)
                    e.printStackTrace();
    //----------- Server
        import java.net.*;
        public class MyServer implements Runnable
            Socket s;
            public MyServer(Socket s)
                this.s = s;
            static public void main(String argv[])
                try
                    ServerSocket ss=new ServerSocket(50080);
                    while(true)
                        Socket s=ss.accept();
                        Thread t = new Thread(new MyServer(s));
                        t.start();
                catch(Throwable e)
                    e.printStackTrace();
            public void run()
                try
                    System.out.println("***socket start");
                    java.io.InputStream ins=s.getInputStream();
                    // Case 1: Does NOT work
                    int j;
                    while((j=ins.read())!=-1)
                        System.out.write(j);
                    // Case 3: Does work
                    while (true)
                        int len = ins.available();
                        if ((len < 0) || s.isClosed()) break;
                        byte b[] = new byte[len];
                        ins.read(b);
                        for (int i=0; i < len; i++)
                            System.out.print((char)b);
    // Case 3: Does work
    while (true)
    int len = ins.available();
    if ((len < 0) || s.isClosed()) break;
    for (int i=0; i < len; i++)
    int b = ins.read();
    System.out.print((char)b);
    System.out.println("***socket end");
    catch(Throwable e)
    e.printStackTrace();

    System.out is line buffered. (I can only hope that I might have noticed this myself if I had been smart enough to use the same output method.)
    Ok so it isn't a socket problem. But I still don't see anything that documents the behavior.
    System.out is documented as a java.io.PrintStream. And that is actually the class that implements it.
    Nothing in the documentation for PrintStream, the methods, the FilterOutputStream or even OutputStream would suggest the different behavior.
    C works the same way; this never prints "world" on most systems:C works that way because of the way file descriptors work and the way that the buffers for those are handled. And how it works is undefined, a C implementation is allowed to handle it anyway it wants.
    But this Java and not C. That means at a minimum that the behavior must be the same on all OSs. But given that the behavior is not documented then it could be that it is left to the implementation of the C library that the java io library is built upon. And that is not a good thing (in terms of normal java.)
    The following demonstrates the behavior using the two output methods...
          String text = "text1\r\ntext2";
          byte[] b = text.getBytes();
          System.out.println("--- print using print() sleep for 10 secs after");
          for (int i=0; i < b.length; i++)
             System.out.print((char)b);
    Thread.currentThread().sleep(10 *1000);
    System.out.println();
    System.out.println("--- print using write() sleep for 10 secs after");
    for (int i=0; i < b.length; i++)
    System.out.write((int)b[i]);
    Thread.currentThread().sleep(10 *1000);
    System.out.println();
    System.out.println("--- done");

  • Best Way to Handle IOException in ServerSocket

    What is the best way to handle IOException thrown by ServerSocket's accept() method?

    Catch it?
    Seriously, it depends what it is. If it's a SocketTimeoutException it's up to you what to do, it's your timeout. If it's some other kind of SocketException or IOException, most probably the socket is dead and all you can do is close it.

  • ServerSocket delay raise socketData event on mac os x 10.9.2

    I have debugged my socket code, connection channel is established, but air.ProgressEvent.SOCKET_DATA event  be raised to receive data with delay 5-20 seconds, 5-20 seconds is not expected in local network.
    Is there other people encounter the same question?  Is this bug causes by air runtime on mac?
    My Js code:
    function TCPServer(port){
      this.server = new air.ServerSocket;
      this.server.addEventListener(air.Event.CONNECT,TCPServer.onReceiveClientConnectionHandler);
      this.server.addEventListener(air.Event.CLOSE,TCPServer.onServerCloseHandler);
      this.server.bind(port);
      this.server.listen();
      this.clients = [];
      this.dispose = function (){
        this.server.close();
        this.server = null;
    TCPServer.onReceiveClientConnectionHandler = function (event) {
      var client = event.socket;
      TCPServer.getInstance().clients.push(client);
      air.trace("client connected.");
      client.addEventListener(air.ProgressEvent.SOCKET_DATA, TCPServer.onTransferDataHandler);
      client.addEventListener(air.Event.CLOSE, TCPServer.onClientCloseHandler);
      client.addEventListener(air.IOErrorEvent.IO_ERROR, TCPServer.onIOErrorHandler);
    //This function delay raise for 5-20 seconds.
    TCPServer.onTransferDataHandler = function (event) {
      air.trace("client received data.");
      var client = event.target;

    Hi daricefrompensacola,
    Are you referring to plugins for Safari or another web browser? If you are talking about Safari you can find them here: http://extensions.apple.com/
    Thanks,
    1212c8

Maybe you are looking for

  • How can I create an App Folder?

    I see you can putt like 8 apps into one folder. I filled up on how can I create another one? Thanks.

  • How to run report from form using run_object_report

    I AM USNING FORMS9I/REPORTS 9I , HOW TO RUN REPORT FROM FROM USING RUN_REPORT_OBJECT AND HOW TO PASS PARAMETER AS WE DID IN RUN_REPORTS PLEASE HELP ME

  • "Broken Reference" when trying to export to iDVD

    I just got iLife 05 and tried to create a DVD from an iMovie I'd made of my daughter's graduation. No matter what I tried (sharing from iMovie, importing in iDVD, opening a new iDVD project and drag/dropping iMovie into iDVD window), I kept getting t

  • I cannot update the BIOS or even reinstall the current BIOS.

    Every available version of the BIOS for my Pavilion dv9612ca claims that it is 'not for this model'  I am trying to resolve an issue where the OS ( Vista 32 bit ) no longer detects the CD/DVD drive. It does show in the BOOT Configuration when I go in

  • Downloading Package Failed

    Hello, I have a Nokia 5500. I already updated my phone a while ago. But when I try it now, the program stops at 'Downloading Update Package Failed'. What can I do, is this a normal error at the moment, or does it comes because I am using Windows Vist