How to close serverSocket/socket?

Hello!
I would like to stop my server and close socket and serversocket
Here is simple code
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
System.out.println("create server socket");          
serverSocket = new ServerSocket(2020);
} catch (IOException e) {
System.err.println("Could not listen on port: 2020");
System.exit(1);
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("listening.....");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
clientSocket.close();
serverSocket.close();
It does not work - just waiting for client requests all time.
How to fix it?
Thanks

Control-C will do it....
But the problem is that the accept method will block waiting for a connection. When you are writing servers, typically you would have several threads. One would hold the server socket and block on accept. When a connection comes in, you would get the client socket and start a new thread to handle that client. Then you still have the main event thread where you would do something to wait for a command (button click, commandline input, etc) to close the server socket.

Similar Messages

  • Security.loadPolicyFile - How to close the socket?

    I use the following code to successfully load the security policy on a remote server:
    Security.loadPolicyFile("https://fm-mgr/ext/crossdomain.xml")
    The problem is that in Firefox, in the status bar, I see that the connection to this server stays open long after the policy file has been loaded. The status bar says "transferring data from fm-mgr..."
    Does anyone know how I can close the socket that that read the policy file?
    Thanks in advance for any help!

    sure... here it is..
    <cross-domain-policy>
         <site-control permitted-cross-domain-policies="all"/>
         <allow-access-from domain="*"/>
         <allow-http-request-headers-from domain="*" headers="*"/>
    </cross-domain-policy>

  • How to close socket, if attempting to accpet clients?

    How do I close the socket if .accept is attempting to try to accept clients:
    //Wait for the acceptance from a client
    clientSocket = serverSocket.accept();
    //In the main thread: User wants to disconnect from chat room
    try{clientSocket.close();}catch(Exception e){ }
    //this is dis-allowed, and throws an exception, how can i get around this?

    After who (client or server) closes what socket? and tries to reconnect what?
    If you close the ServerSocket, future connects will fail.
    If you close the client (accepted) socket, the client will read an EOS condition.
    If you try to open a new ServerSocket on the same port without closing the old one, you will get a BindException.
    As I have no idea what you're actually doing I can't help any further. Post the (reduced to minimal) code and the stack trace, and show which line of code is incurring the exception.

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

  • How to close other thread's InputStream?

    Hi,
    I am developing a multithreaded "JAVA CONSOLE APPLICATION".
    Brief description of application is like this:
    On initialising, application starts a new thread. In that it listens for the keyboard input from the user(System.in.read()). But it listens only for some time (5 seconds). After this time, this should be stopped and in main thread which is listening for the server application, should display information from the server and listen for the keyboard input from the user.
    But the problem is, it listens for two keyboard inputs. 1 in main thread and another in other thread as it doesn't get closed even though the thread is stopped.
    So how to close that InputStream so that application should listen for keyboard only in main thread?
    Thanx in Advance,
    Sameer Mahajan

    Not really sure if this works, as your description isn't clear.
    But for sockets, the following works :
    public void run { //the Threads/Runnable run method
       try {
          //do your stuff
       } finally {
          try {
             is.close(); //supposed 'is' is your InputStream
          } catch (IOException e) {}
    }Now, whenever the thread terminates, the InputStream will be closed.
    Maybe even if you use Thread.stop(), but this is deprecated,
    so better use Thread.interrupt() and flags.

  • How to close all running threads

    I have many threads running everywhere in my application. when i disconnect from server, all sockets between me and the server must disconnect. but since different threads are having a socket connection each to the server, i cant close them all, since i dont have the reference to the diff thread objects.
    how do i close these sockets (each whole thread) ?
    Regards,
    Sid

    Thanks for replying.
    but i figured out the way last night itself.
    i was trying to fire a text changed event and putting a listener for it in every running thread so that when i want to disconenct, i would write some text into the textbox which would fire the event and the threads would listen to itr and kill themselves. but it simply wasnt workin.
    then i came across the class ThreadGroup. add each thread to that threadgroup adn say ThreadGroup.stop();
    Thanks anyway.
    Regards,
    Sid

  • How use multithead with socket

    How use multithead with socket
    I need do a client and server program that accept multitherad issue
    Thanks who can help me

    you'd have to do something like this:
    (this is all assuming you want to read Strings from the socket. setSoTimeout works for any read() call to the InputStream associated with the Socket)
    ServerSocket ss = new ServerSocket(myPort);
    Socket s = ss.accept();
    s.setSoTimeout(5*60*1000); // 5 mins * 60 secs * 1000ms
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    boolean running = true;
    while(running)
    try
    String readIn = in.readLine();
    // do whatever you want with the data read
    catch(SocketTimeoutException)
    running = false;
    Now. That's what I think needs to be done. I don't have Java on the machine I'm currently on, so I can't test/verify it, but it goes something like that.
    Good luck,
    Radish21

  • How to close extended classic PO in ECC...

    Hi Friends...
    We are in SRM 7.02 and ECC 6.05 in Extended Classic Scenario. One PO had been created for 1 Quantity 3 years ago. There was no GR/IR document posted against that PO. Now that PO had been archieved from SRM. But still PO is available in ECC with open quantity and also its appearing in the open PO report. Now requester wanted, the PO to be closed in ECC and shouldnot appear in the open PO list.
    How to handle this situation.. How to close the extended classic PO in ECC at this scenario. As PO not available in SRM, we can not do anything from SRM side.
    Your inputs are appreciated....
    Regards
    Sivakumar Kandasamy

    Hi Sivakumar,
    If you mean how to archive PO in MM side, please refer to the following info:
    ====
    In ECC system, if you want to archive a MM PO, please use transaction
    SARA->archive object MM_EKKO.
    456129 FAQ: Archiving in purchasing
    401318 Archiving: Additional information
    ====
    If you want to delete this ECC PO, please use BAPI_PO_CHANGE and
    refer to the following test data:
    Parameters:    PURCHASEORDER      =  XXXXXXXXX
    Parameters:    POITEM
    PO_ITEM                        = 00010
    DELETE_IND                     = X
    Parameters:    POITEMX
    PO_ITEM                        = 00010
    PO_ITEMX                       = X
    DELETE_IND                     = X
    You also need to run BAPI_TRANSACTION_COMMIT after BAPI_PO_CHANGE for updating the change.
    Regards,
    Ivy

  • After the update I don't know how to close running apps? I recall double clicking the main button then hold one app until they begin a jiggling motion. But that no longer works.

    How do close running apps?

    You still double tap the home button and the apps are lined up across the screen. Swipe up on the app preview thumbnail - drag it up off of the screen - and that will close the app.

  • How to close iOS7 apps?

    Prior to iOS7 you simply double clicked the home button to show open Apps and you could then close them all down.  That doesn't seem to happen with iOS7.  Any idea how to close open Apps?
    ... The learning curve beings

    Thanks ...
    That's what I was trying, but I guess I was doing so to quickly.  Once I slowed down they finally moved.  Now ... if the former Apps wouldn't crash I'd be all set, ROFL.  Going to be a learning curve for the developers as well I think.
    So much to learn

  • Can anyone advise how to close apps on iPad with new iOS? I have multiple open and cannot close them.

    Can anyone advise how to close apps with the new iOS?  I have multiple open and cannot close them

    Double-tap on the Home button. You will see a preview of the app above the actual icon. Slide the preview up to kill it.
    Please get the iPhone User Guide (For iOS 7 Software)Sep 19, 2013 - 23 MB.

  • How to close sidebar under ios 8 in order to use the whole screen for reading?

    How to close sidebar under ios 8 so that i can have the full screen for reading?

    Sidebar where?
    In Safari?Tap on the Blue open book icon at the very top of the screen. There are two such icons, it is the one on top you want to tap to close the sidebar.

  • How to close email notifications to senders from HP eprintCenter?

    Hi,
    How to close email notifications to senders from HP eprintCenter?
    Thank you.

    Hi Jack7363,
    Welcome to the HP Support Forums. I gather that you would like to know how to turn off notifications from HP’s ePrintCenter.
    To better assist you, would you please supply some additional information:
    What make/model/product number of HP printer do you have? How Do I Find My Model Number or Product Number?
    How is the printer connected (USB cable, ethernet, or wireless)?
    Do you have an HP Connected account or HP ePrintCenter account?
    Are the emails coming [email protected]?
    Thank you.
    Regards,
    Happytohelp01
    Please click on the Thumbs Up on the right to say “Thanks” for helping!
    Please click “Accept as Solution ” on the post that solves your issue to help others find the solution.
    I work on behalf of HP

  • How to close apps on iPhone 4

    I tried everything it says from the web from pressing the hold button 2 times and bottom shows the apps but cannot get the minus sign or get them to wiggle like people say anyone know how to close apps like this. mINE DOES NOT WORK SUPPOSE TO GET A MINUS SIGN OR HOLD TO WIGGLE NO LUCK.

    Maybe a visual will help: https://sites.google.com/site/appleclubfhs/support/advice-and-articles/locking-o rientation

  • How to close goods receipt PO

    Hi All,
    We are using SAP 8.8
    how to close Goods Receipt PO that has been pulled to A/P Invoice with a partial amount of freight ?
    i.e.
    Our GRPO has freight 5000.
    On pressing COPY FROM button in A/P invoice we selected that GRPO
    On Pressing Customize button
    Items in the GRPO appear
    We selected all items and press next
    Freight appears
    We edited freight amount from 5000 to 3000 and pulled GRPO into invoice and saved.
    After this OUR GRPO and freight remains
    Guidance in this is really needed as we want to tally stock
    Thanks
    Malhaar

    Hi Malhaar......
    Does it happen all the time like this reversal of entry?
    Like how you tested in demo this kind of scenario I would suggest you to do this excercise too.
    So that you get knowledge about that and Today you are asking this doubt but after doing this excercise you will come to know the exact effect and next time you can suggest this to others if he has same problem and will become expert in SAP
    All the Best
    Regards,
    Rahul

Maybe you are looking for