ServerSocket problem.

Hi,
I have written a small server program using the java.net.ServerSocket class. The server can serve simple servlets and html pages.
I am creating the ServerSocket instance like this:
ServerSocket ss = new ServerSocket(port_no, acceptCount, InetAddress.getByName("webserver"));The hostname of the computer on which this program runs is "webserver", ip address is "192.168.100.150".
When I send request for a basic servlet using either "127.0.0.1" or "webserver" it works. But it displays a 'Page cannot be displayed" error when I try to use "localhost" or "192.168.100.150" in the url.
ex:
This works:
http://127.0.0.1:8888/FirstApp/SampleServlet
http://webserver:8888/FirstApp/SampleServlet
Does'nt work:
http://192.168.100.150:8888/FirstApp/SampleServlet
http://localhost:8888/FirstApp/SampleServlet
Please help me with the problem. I've tried using different options with the ServerSOcket constructors and methods but always I miss one or the other.
I would like my server program to server requets sent for localhost/127.0.0.1/webserver/192.168.100.150, please guide me as to what should I do to acheive this.
Thanks a lot.

ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=8888]
Can you see something wrong with this output? I was
expecting the ip address of the computer to be bound
to the ServerSocket instance but surprisingly it is
0.0.0.0.There is nothing wrong with this output. The ServerSocket is bound by default to the 'wildcard' address which is represented as above and which means it will accept connections via any of the computer's interfaces. This is what you want. The way you had it before it would only accept connections via one interface.
As _ck clearly doesn't know the answer himself his contribution is valueless and is best ignored.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Iptables ServerSocket problem

    hello all,
    I've also put this in general programming as didn't know where was the best place for it....
    I am having a problem getting iptables to accept an incoming port connection from java. I have a java program that creates a ServerSocket as follows:
    public NetworkServer()
    try
    InetAddress addr = java.net.InetAddress.getByName("localhost");
    server = new ServerSocket(1050,0,addr);
    System.out.println("server = " + server);
    System.out.println("connection successful");
    catch(Exception ioe)
    System.out.println("error connecting to port 1050 : " + ioe);
    I have set up iptables with the following commands to let allow this connection through:
    iptables -P INPUT DROP
    iptables -A INPUT -d localhost -p tcp --dport 1050 -j ACCEPT
    iptables -A INPUT -d localhost -p tcp --sport 1050 -j ACCEPT
    the forward and output tables have default accept policies with no other governing rules.
    The outcome of this is that the ServerSocket tries to connect to the address from InetAddress.getByName, which is retrieved as "localhost/127.0.0.1", and after 3 mins with the following output:
    server=[addr=localhost/127.0.0.1,port=0,localport=1050]
    I saw a previous post on this forum regarding iptables stating that packets are dropped after 3 minutes if no reply is received. But if this is true and this is what is happening, I don't see why the socket is being set up? No exception occurs.
    As the "port" number is 0, I tried adding entries in iptables for 0 also, but this doesn't make any difference. I understand that ServerSockets may make connections on different ports to clients, but the output says that it has (tried to) set up a connection on port 1050.....
    I was thinking it may have a problem with the inet address, as it has both the name and IP address of the localhost, and maybe iptables just needs one of these as an input parameter? However an InetAddress can only be constructed from one of the native methods provided so has to be in this format.
    any ideas gratefully appreciated, I am completely flummoxed!!!

    DO NOT set you server to start port addressing at 0. Zero (0) is used to specify "any" port. This however, is usually a sequential port number starting at the first open port on your system. However, I have no cluse as to what "iptable" is - is that a system utility used to edit filters on the machine? What system is that? Linux or Unix? I know of no such command for Windows-based machines.
    When developing network applications, it is best to use a non-secure machine to test the programming. This way you can systematically understand the affects of certain network security functions on your program.
    What is happening is that you are telling iptables to open a source port that is the same as incomming port requests, but fail to open the ports that '0' will address. If you know what the first available port number is on your system (these are after the Well-Known ports, and after all of the server and client ports already open). Also, depending on your system configuration, it may seek a open block of ports, about 10 and if none exists then looks for 5-blocks, then 2-blocks, and finally resorts to the first open port it sees start just after the WKP.

  • Iptables/ServerSockets problem

    hello all,
    I've also put this post in the java programming forum as I didn't know which was more appropriate, sorry for duplication if you've read it elsewhere...
    I am having a problem getting iptables to accept an incoming port connection from java. I have a java program that creates a ServerSocket as follows:
    public NetworkServer()
    try
    InetAddress addr = java.net.InetAddress.getByName("localhost");
    server = new ServerSocket(1050,0,addr);
    System.out.println("server = " + server);
    System.out.println("connection successful");
    catch(Exception ioe)
    System.out.println("error connecting to port 1050 : " + ioe);
    I have set up iptables with the following commands to let allow this connection through:
    iptables -P INPUT DROP
    iptables -A INPUT -d localhost -p tcp --dport 1050 -j ACCEPT
    iptables -A INPUT -d localhost -p tcp --sport 1050 -j ACCEPT
    the forward and output tables have default accept policies with no other governing rules.
    The outcome of this is that the ServerSocket tries to connect to the address from InetAddress.getByName, which is retrieved as "localhost/127.0.0.1", and after 3 mins with the following output:
    server=[addr=localhost/127.0.0.1,port=0,localport=1050]
    I saw a previous post on this forum regarding iptables stating that packets are dropped after 3 minutes if no reply is received. But if this is true and this is what is happening, I don't see why the socket is being set up? No exception occurs.
    As the "port" number is 0, I tried adding entries in iptables for 0 also, but this doesn't make any difference. I understand that ServerSockets may make connections on different ports to clients, but the output says that it has (tried to) set up a connection on port 1050.....
    I was thinking it may have a problem with the inet address, as it has both the name and IP address of the localhost, and maybe iptables just needs one of these as an input parameter? However an InetAddress can only be constructed from one of the native methods provided so has to be in this format.
    any ideas gratefully appreciated, I am completely flummoxed!!!

    hi, thanks for the info....
    I needed to block all input on the localhost for testing purposes as I only had 1 pc for both client and server applications. I've now realised this won't work as the localhost needs certain things running on certain ports so I can't block too much - my java editor wouldn't even run!
    I am in the middle of setting up a network so I can block access to stuff from external IP addresses. Hopefully this should work a bit better :)
    cheers,
    Bec.

  • AIR 2.5.1 ServerSocket Problem

    Hey Guys, Something Really funny just happened to my AIR/ FlashBuilder Installation, I've got Flex 4 / Flash Builder on my system, I've also got AIR 2.5.1 on my system too, my flash builder IDE doesnt seem to find ServerSocket Class....
    I tried to Check the Current Version of AIR using nativeApplication.runtimeVersion andd it says 1.5
    Those anyone have anuy idea what the problem is?

    I have the same problem. When I run my project from Flash Professional CS5 works fine but when I publish the project to an AIR application the ServerSocket does not work (any client could connect to it).

  • ServerSocket problems accepting 2 client at the same time

    hi all,
    i wrote a simple client-server pair, to synchronize databases, and works fine.
    but i found a problem: all ok when 2 clients try to connect to the server whit a little gap (ie 1 second), the problem is when they try to connect EXACTLY at the same time
    while (true)
                enter();
    synchronized void enter()
            try
                    client=server.accept();
                    thread_name++;
                    s_newport np=new s_newport(client,
                    ((new Integer(thread_name)).toString()));               
                catch (IOException io)
                catch (NullPointerException np)
        }when a request is accepted, an instance of the class s_newport (a thread) starts to open another socket.
    the problem is when 2 requests arrive in the same moment, and the server doesn't accept anything.
    i declared the enter() method synchronized, but this doesn't seem to work!
    anyone could help me please?
    thanks
    sandro

    excuse me, i didn't understand...
    thanks for your reply
    sandro

  • ServerSocket problem, please help, thanks a lot

    Hi,
    My program has a method as follow:
    private ServerSocket serverSocket;
    public void Connecting( )
    . try
    . serverSocket = new ServerSocket(1234);
    . catch (Exception e) {}
    . while (true)
    . try
    . Socket socket = serverSocket.accept();
    . socket.close();
    . break;
    . catch (Exception e) {System.out.println(e.getMessage( );}
    The first time I called this method, it worked fine. But the second time I called this method, it didn't work. An exception was caught and I got the message as follow:
    Address already in use: JVM_Bind
    Would you please advise how I can change the method so that each time I call this method and the serverSocket will be able to setup correctly (given that I want to use the same port again and again) ?
    Thanks for your help.
    Regards,
    Jackie

    sigh
    Continue in original thread:
    http://forum.java.sun.com/thread.jspa?threadID=703568

  • Problem with ServerSocket.accept

    Hi, I'm from Italy so I apologize for my English.
    The problem is this, I created a separated Thread to listen the connections that come from the various clients, when it receive a connection it creates a new Thread to manage the connection.
    The problem is that I need to stop the Thread (the one that look for new connetions), whenever I need it, but how can i do it if the method ServerSocket.accept(); stop the execution of the thread.
    The listener of new connections extends Thread and this is the run method overridden.
    public void run() {
         ServerSocket ss;
         Server myServer; /* Another class that extends Thread to manage the connection */
         while (true) {
              try {
                   ss = new ServerSocket(port, queueLength);
                   Socket sd = ss.accept();
                   myServer = new Server(sd);
                   myServer.start();
              catch (IOException e) {
    }

    public void run() {
        ServerSocket ss;
        Server myServer;
        /* Another class that extends Thread to manage the connection */
        while (true) {
            try {
                ss = new ServerSocket(port, queueLength);
                Socket sd = ss.accept();
                myServer = new Server(sd);
                myServer.start();
            catch (IOException e) {
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • ServerSocket OSx problem

    Hi,
    I have an application that use flash.net.ServerSocket class, in my test suite when i reuse the address/port used by ServerSocket
    the application fails with "#2002: Operation attempted on invalid socket.", these only appers to happen in OSx , in Windows 7 the
    same test works fine.
    Seem my test case bellow, the error happens the second time server.bind is called, any ideas, is there something wrong with that
    code?
    <?xml version="1.0" encoding="utf-8"?>
    <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                           xmlns:s="library://ns.adobe.com/flex/spark"
                           xmlns:mx="library://ns.adobe.com/flex/mx">
        <fx:Script>
            <![CDATA[
                private var server:flash.net.ServerSocket;
                private var client:flash.net.Socket;
                private var i:int;
                public function init():void
                    i = 0;
                    log.text = "";
                    doTest();
                public function doTest():void
                    try
                        log.text += "socket " + i.toFixed() + "\n";
                        server= new ServerSocket();
                        server.addEventListener(Event.CLOSE, serverClose);
                        server.bind(10011, "127.0.0.1");
                        server.listen(511);
                        client = new Socket();
                        client.addEventListener(Event.CONNECT, connected);
                        client.addEventListener(IOErrorEvent.IO_ERROR, ioError);
                        client.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
                        client.connect("127.0.0.1", 10011);
                        i++;
                    catch(ioe:IOError)
                        log.text += ioe.toString() + "\n";
                    catch(e:Error)
                        log.text += e.toString() + "\n";   
                public function ioError(e:IOErrorEvent):void
                    log.text += "IO error " + e.toString() + "\n";
                public function securityError(e:SecurityErrorEvent):void
                    log.text += "Security error " + e.toString() + "\n";
                public function connected(e:Event):void
                    server.close();
                    if(i < 100)
                        doTest();
                public function serverClose(e:Event):void
                    log.text += "Server close ok\n";
            ]]>
        </fx:Script>
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <s:VGroup>
            <s:TextArea id="log" width="100%" height="100%">
            </s:TextArea>
            <s:Button click="init()" label="Start">
            </s:Button>
        </s:VGroup>
    </s:WindowedApplication>

    Hello,
    Thanks for your reporting. The operation system does need some time to create a socket or close a socket. It may need more time to close a socket on Mac OS than that on Windows. To verify this, we just modify your code to make the "Start" only call the "doTest" once. Then we found if clicking "Start" fast on Windows, then "#2002: Operation attempted on invalid socket" would also appear, while if clicking "Start" slow on Mac OS, the application would work fine without the error. Please also have a try for that.
    Thanks!

  • Serversocket read problem

    I create a socket connection that listens for commands that sends from the client. I try to printout the command while it is reading it. ... However, I can only see the printout after I stop the client sending commands. The socket will receive a long commands that each small command is seprated by '/r'.
    I also try to put it in debug mode, it looks like it is stuck in the read method....
    public class SocketSim
         public static final int PORT = 2000;
         public static void main(String[] args)
              throws IOException
              ServerSocket ss = new ServerSocket(PORT);
              Socket accept = ss.accept();
              System.out.println("Server socket opened and ready on " + PORT);
              for (;;)
                   try
                        accept = ss.accept();
                        processRequest(accept);
                   catch (Exception e)
                        System.err.println(e);
                   finally
                        if (null != accept) try { accept.close(); } catch (Exception e) { System.err.println("Failed socket close()"); }
         static void processRequest(Socket s) throws IOException
              InputStream is = s.getInputStream();
              String req="";
              int i = 0;
              while (i != -1)
                   int j = is.read();
                   char c = (char) j;
                   if (j != -1)
                        req += c;
                   if (c == '\r')
                        System.out.println("each request: " + req);
                        req = "";
              } /* while */
         }

    In this case, I have no idea. Let's see what others have to say.
    In the meantime, you can try two things:
    1. Use a Telnet client (like the one that comes with Windows) to send something to your java server.
    If now read() returns, there is something fishy with the C++ client or some configuration issue.
    If it does not, yes, it's your server, but I don't see why.
    2. Use a network monitor such as wireshark to see who is sending what to whom.
    Edited by: baftos on Nov 2, 2009 2:49 PM

  • Runtime.exec and ServerSocket for IPC...blocking problems

    I have built an IDE for assembling/deploying web applications.
    I am supporting a 'test' mode in the IDE where a compiled 'solution/application' is executed in a separate vm from the IDE using Runtime.exec. For the whole sandbox thing. Don't want a wayward application crashing my IDE.
    Naturally I want a way to communicate start/stop from the IDE to the running application. So sockets are my only choice. Calling process.destroy from my IDE won't invoke a shutdownhandler in the generated application's vm, and I want an orderly shutdown as the generated applications open resources/etc.
    When I execute the generated application from within the IDE the thread code that creates a server socket blocks in the ServerSocket constructor...why?
    When I execute the solution using 'java' outside of my IDE, I can set up a server socket and all works fine.
    My IDE is NEVER creating server sockets waiting for client connects...only the generated application does this. So it isn't a case of the IDE already listening for requests on the same port as the server/generated application.
    Proving the above is that I can manually start my generated application, start my ide, then invoke the menuitem from the IDE that writes a 'close' byte to the client's socket...and the running application DOES shut down.
    Any ideas?

    I have decided on a different approach.
    At first I thought...ok I have the ServerSocket on the wrong 'side'. I then put the ServerSocket code in the always-running IDE and the Socket code on the running/exec'd application. But still a hang on the running application when constructing the Socket.
    I decided instead to call Process.destroy on the running app.
    Given that generated app is running in a separate vm, when it shuts down via process.destroy from the ide...although vm shutdown hooks aren't called...I guess it's ok since a destroy of the vm will release all resources. Not as clean as I'd like though.
    Additionally, I cannot determine 'true' start of application as no socket notification can be done. I merely determine start after a Runtime.exec of jvm process. Subsequent errors in startup will merely be determined by the IDE in process.waitFor or process.exitValue.
    I was getting a wierd socket error when attempting my prior solutions...and not a lot on the web regarding this subject...all relevant posts seemed to be in German/from Germany. Odd. Would need my wife to translate! Mein gott!
    I guess I could've communicated from ide to Runtime.exec'd application via a generated file in filesystem...but this seemed cheesy. Sockets should've been used for ipc between java vms...or so I thought.

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • Problem with threads running javaw

    Hi,
    Having a problem with multi thread programming using client server sockets. The program works find when starting the the application in a console using java muti.java , but when using javaw multi.java the program doesnt die and have to kill it in the task manager. The program doesnt display any of my gui error messages either when the server disconnect the client. all works find in a console. any advice on this as I havent been able to understand why this is happening? any comment would be appreciated.
    troy.

    troy,
    Try and post a minimum code sample of your app which
    does not work.
    When using javaw, make sure you redirect the standard
    error and standard output streams to file.
    Graeme.Hi Graeme,
    I dont understand what you mean by redirection to file? some of my code below.
    The code works fine under a console, code is supposed to exit when the client (the other server )disconnects. the problem is that but the clientworker side of the code still works. which under console it doesnt.
    public class Server{
    ServerSocket aServerSocket;
    Socket dianosticsSocket;
    Socket nPortExpress;
    ClientListener aClientListener;
    LinkedList queue = new LinkedList();
    int port = 0;
    int clientPort = 0;
    String clientName = null;
    boolean serverAlive = true;
    * Server constructor generates a server
    * Socket and then starts a client threads.
    * @param aPort      socket port of local machine.
    public Server(int aPort, String aClientName, int aClientPort){
    port = aPort;
    clientName = aClientName;
    clientPort = aClientPort;
    try{
    // create a new thread
    aServerSocket = new ServerSocket(port) ;
    // connect to the nPortExpress
    aClientListener = new ClientListener(InetAddress.getByName(clientName), clientPort, queue,this);
    // aClientListener.setDaemon(true);
    aClientListener.start();
    // start a dianostic port
    DiagnosticsServer aDiagnosticsServer = new DiagnosticsServer(port,queue,aClientListener);
    // System.out.println("Server is running on port " + port + "...");
    // System.out.println("Connect to nPort");
    catch(Exception e)
    // System.out.println("ERROR: Server port " + port + " not available");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Server port " + port + " not available", JOptionPane.ERROR_MESSAGE);
    serverAlive = false;
    System.exit(1);
    while(serverAlive&&aClientListener.hostSocket.isConnected()){
    try{
    // connect the client
    Socket aClient = aServerSocket.accept();
    //System.out.println("open client connection");
    //System.out.println("client local: "+ aClient.getLocalAddress().toString());
    // System.out.println("client localport: "+ aClient.getLocalPort());
    // System.out.println("client : "+ aClient.getInetAddress().toString());
    // System.out.println("client port: "+ aClient.getLocalPort());
    // make a new client thread
    ClientWorker clientThread = new ClientWorker(aClient, queue, aClientListener, false);
    // start thread
    clientThread.start();
    catch(Exception e)
    //System.out.println("ERROR: Client connection failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client connection failure", JOptionPane.ERROR_MESSAGE);
    }// end while
    } // end constructor Server
    void serverExit(){
         JOptionPane.showMessageDialog(null, "Server ","ERROR: nPort Failure", JOptionPane.ERROR_MESSAGE);
         System.exit(1);
    }// end class Server
    *** connect to another server
    public class ClientListener extends Thread{
    InetAddress hostName;
    int hostPort;
    Socket hostSocket;
    BufferedReader in;
    PrintWriter out;
    boolean loggedIn;
    LinkedList queue;      // reference to Server queue
    Server serverRef; // reference to main server
    * ClientListener connects to the host server.
    * @param aHostName is the name of the host eg server name or IP address.
    * @param aHostPort is a port number of the host.
    * @param aLoginName is the users login name.
    public ClientListener(InetAddress aHostName, int aHostPort,LinkedList aQueue,Server aServer)      // reference to Server queue)
    hostName = aHostName;
    hostPort = aHostPort;
    queue = aQueue;
    serverRef = aServer;      
    // connect to the server
    try{
    hostSocket = new Socket(hostName, hostPort);
    catch(IOException e){
    //System.out.println("ERROR: Connection Host Failed");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort Failed", JOptionPane.ERROR_MESSAGE);     
    System.exit(0);
    } // end constructor ClientListener
    ** multi client connection server
    ClientWorker(Socket aSocket,LinkedList aQueue, ClientListener aClientListener, boolean diagnostics){
    queue = aQueue;
    addToQueue(this);
    client = aSocket;
    clientRef = aClientListener;
    aDiagnostic = diagnostics;
    } // end constructor ClientWorker
    * run method is the main loop of the server program
    * in change of handle new client connection as well
    * as handle all messages and errors.
    public void run(){
    boolean alive = true;
    String aSubString = "";
    in = null;
    out = null;
    loginName = "";
    loggedIn = false;
    while (alive && client.isConnected()&& clientRef.hostSocket.isConnected()){
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
    if(aDiagnostic){
    out.println("WELCOME to diagnostics");
    broadCastDia("Connect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    out.println("WELCOME to Troy's Server");
    broadCastDia("Connect : client "+client.getInetAddress().toString());
         out.flush();
    String line;
    while(((line = in.readLine())!= null)){
    StringTokenizer aStringToken = new StringTokenizer(line, " ");
    if(!aDiagnostic){
    broadCastDia(line);
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    else{
    if(line.equals("GETIPS"))
    getIPs();
    else{
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    } // end while
    catch(Exception e){
    // System.out.println("ERROR:Client Connection reset");
                             JOptionPane.showMessageDialog(null, (e.toString()),"ERROR:Client Connection reset", JOptionPane.ERROR_MESSAGE);     
    try{
    if(aDiagnostic){
    broadCastDia("Disconnect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    broadCastDia("Disconnect : client "+client.getInetAddress().toString());
         out.flush();
    // close the buffers and connection;
    in.close();
    out.close();
    client.close();
    // System.out.println("out");
    // remove from list
    removeThreadQueue(this);
    alive = false;
    catch(Exception e){
    // System.out.println("ERROR: Client Connection reset failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client Connection reset failure", JOptionPane.ERROR_MESSAGE);     
    }// end while
    } // end method run
    * method run - Generates io stream for communicating with the server and
    * starts the client gui. Run also parses the input commands from the server.
    public void run(){
    boolean alive = true;
    try{
    // begin to life the gui
    // aGuiClient = new ClientGui(hostName.getHostName(), hostPort, loginName, this);
    // aGuiClient.show();
    in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(hostSocket.getOutputStream()));
    while (alive && hostSocket.isConnected()){
    String line;
    while(((line = in.readLine())!= null)){
    System.out.println(line);
    broadCast(line);
    } // end while
    } // end while
    catch(Exception e){
    //     System.out.println("ERRORa Connection to host reset");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort reset", JOptionPane.ERROR_MESSAGE);
    try{
    hostSocket.close();
         }catch(Exception a){
         JOptionPane.showMessageDialog(null, (a.toString()),"ERROR: Exception", JOptionPane.ERROR_MESSAGE);
    alive = false;
    System.exit(1);
    } // end method run

  • Connection Problem while client is behind proxy and server out side proxy

    hello
    i implemented ChatApplication in JAVA, for that i used socket connection when client and server both are in same network then it's working fine.
    but when my server is on internate and client is behind proxy and try to connect with server
    it not able to connect i get exception.
    i serch most of forum i got same answer and i try it but i was not success.
    any kind of help is appriciated.
    i attached my code(which i implement for testing ) pls reply me
    thanks in advance.
    Server.java
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    class Server {
       public static void main(String args[]) {
          String data = "you are successfully connected with server.";
          try {
             ServerSocket srvs = new ServerSocket(1234);
             Socket skt = srvs.accept();
             System.out.print("Server has connected!\n");
             PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
             System.out.print("Sending string: '" + data + "\n");
             out.print(data);
             out.close();
             skt.close();
             srvs.close();
          catch(Exception e) {
             System.out.print("Whoops! It didn't work!\n");
    ProxyClient.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class ProxyClient{
       public static void main(String args[]) {
         String host="61.17.212.29";
         int port=1234;
               String line;
         Properties properties = System.getProperties();
         /*properties.put("firewallSet", "true");
         properties.put("firewallHost", "192.168.0.1");
         properties.put("firewallPort", "808");*/
         properties.put("socksProxySet","true");
         properties.put("socksProxyHost", "192.168.0.1");
         properties.put("socksProxyPort", "1080");
         System.setProperties (properties);
         try {
         /*SocketAddress addr = new InetSocketAddress("192.168.0.1", 1080);
         Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
         Socket skt = new Socket(proxy);
         InetSocketAddress dest = new InetSocketAddress("61.17.212.29",1234);
         skt.connect(dest);*/
             System.out.println("before socket taken");
             Socket skt = new Socket(host,port);
             System.out.println("after socket taken");
             BufferedReader networkBin = new BufferedReader(new InputStreamReader(skt.getInputStream()));
             System.out.println("Received string: '");
             line = networkBin.readLine();     // Read one line
          while(true)
                 System.out.println(line);     // Output the line
                 line = networkBin.readLine(); // Read the next line, if any
          catch(Exception e) {
             System.out.print("Whoops! It didn't work!\n");
         e.printStackTrace();
    }

    Now look here. I could not care less about this
    code. I don't know anything about it, I don't
    want to know, I have already recommended you don't
    use it, and I have also given you a simpler and
    better solution. If you don't want to take my advice
    that is your privilege and your problem.ya i has understand system propertis i have setted and u can see it in the code i have tried by both system properties and also J2SE 5.0 proxy class but i got a same problem malformed Exception server refuse to connection.
    is there any problem at sever side?
    can u tell me in which way u r teling to set the propery i m looking forward for ur reply.
    ya i m sure u will give me.................reply "ejp".
    Thnx in advance.

  • Problem with socket programming(Vista)

    I'm not sure if this has something to do with windows vista.
    I wrote simple echo client and server programs and the client program contains these lines
    String hostname="172.16.54.22"; //My comp's IP
    int portNo=6666;
    mySocket=new Socket(hostname, portNo);
    Now the problem is that the client program is able to communicate with the server only when I run both of them in xp machines or if I run the server in vista and client in xp. The client is not able to connect to the server when both the client and server are running in a vista machine or if the server is running in xp and client in vista.
    It'd be nice if any of you could throw some light on this issue.
    PS:
    It doesn't work even if I turn the firewall off
    The programs work well when I give hostname="localhost" or hostname="127.0.0.1"
    Here are my programs
    //EchoClient.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class EchoClient
         public static void main(String args[])
              String hostname="172.16.54.25"; //My ip address
              int portNo=6666;
              //if(args[1]
              //PrintWriter out=null;
              Socket mySocket=null;
              BufferedReader networkIn=null;
              BufferedReader userIn=null;
              PrintWriter sockOut=null;
              try
                   mySocket=new Socket(hostname, portNo);
                   networkIn=new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
                   userIn=new BufferedReader(new InputStreamReader(System.in));
                   sockOut= new PrintWriter(mySocket.getOutputStream());
                   System.out.println("Connected to Echo Server\n");
                   System.out.println("Enter a series of lines (\"end\" to exit)\n");
                   while(true)
                        String myLine=userIn.readLine();
                   //     System.out.println(myLine);
                        if(myLine.equals("end"))
                             break;
                        sockOut.println(myLine);
                        sockOut.flush();
                        System.out.println(networkIn.readLine());
              catch(IOException exc)
                   System.err.println(exc);
              finally
                   try{
                   if(networkIn!=null) networkIn.close();
                   if(sockOut!=null) sockOut.close();}
                   catch(IOException exc){ }
                   EchoServer.java
    //EchoServer.java
    import java.io.*;
    import java.net.*;
    class EchoServer
         public static void main(String args[])
              int portNo=6666;
              ServerSocket serverSock=null;
              try
                   serverSock=new ServerSocket(portNo);
                   System.out.println("Echo Server Started\n\n");
                   while(true)
                        Socket clientSock=serverSock.accept();
                        new Thread(new EchoServerThread(clientSock)).start();
              catch(IOException exc)
                   System.err.println(exc);
         EchoServerThread.java
    //EchoServerThread.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class EchoServerThread implements Runnable
         public Socket clientSock;
         EchoServerThread(Socket sock)
              clientSock=sock;
         public void run()
              System.out.println("\nAccepted Connection from a Client");
              try{
              BufferedReader in=new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
              BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in));
              PrintWriter out= new PrintWriter(clientSock.getOutputStream());
                        /*In sockIn=new In(clientSock);
              Out sockOut=new Out(clientSock);*/
              String str;
              while((str=in.readLine())!=null)
                   out.println(str);
                   out.flush();
              System.out.println("Closing Connection from a Client");
              out.close();
              in.close();
              catch(IOException exc)
                   System.err.println(exc);
         

    Sorry everyone but I'd been giving a wong IP address thinking it's my own. The problem's solved.
    Thanks for the response Peter.

  • Problem with socket communications

    I am trying to put together a client server socket communication pair.
    I have one application that runs in the background acting as a server and another that can be started and stopped that acts as a client.
    I can start the server and create a server socket with no problem.
    I can start the client and it connects to the server.
    The server acknowledges the connection and appears to go into a blocking state waiting for the client to send another message.
    The server blocks at the line
    parent.logit("Waiting for message from EVR..... ");
    The problem is that when the client sends another message, the server doesn't hear it.
    I am not sure if the problem is with the client or server communication code.
    If anyone out there is a socket communication guru, I would appreciate it if you could tell me what I am doing wrong.
    Thanks
    Server code:
    import java.io.*;
    import java.net.*;
    public class EVRServer
        extends Thread
      EVRDataLoader parent = null;
      ServerSocket serverSock = null;
      Socket clientSock = null;
      BufferedReader reader = null;
      BufferedWriter writer = null;
      int evrPort = 0;
      int retryLimit = 10;
      int retryCount = 0;
      boolean alive = false;
      boolean killSocket = false;
      boolean evrConnected = false;
      boolean retry = true;
      EVRListener evrListener = null;
    //=============================================================================
    // Full constructor
    //=============================================================================
       * Full constructor.
       * @param dl DataLoader - Parent application
       * @param port int Socket port
      public EVRServer(EVRDataLoader dl, int port)
        parent = dl;
        evrPort = port;
    //=============================================================================
    //  Run method - Main thread executed by start() method
    //=============================================================================
       * Main thread executed by start() method
      public void run()
        while (retry)
          if (retryCount > retryLimit)
            retry = false;
          parent.logit("Retry count = " + retryCount);
          // Create new server socket connection
          if (serverSock == null)
            try
              serverSock = new ServerSocket(evrPort);
              parent.logit("Created Server Socket for EVR on port " + evrPort);
              alive = true;
              killSocket = false;
              evrConnected = false;
            catch (Exception e)
              parent.logit(
                  "ERROR - Could not create Server socket connection for EVR: " +
                  e.toString());
              killSocket = true;
              alive = false;
          // Create new client socket connection
          if (clientSock == null)
            try
              parent.logit("Waiting for EVR to connect");
              clientSock = null;
              clientSock = serverSock.accept();
              retryCount = 0;
              evrConnected = true;
              killSocket = false;
              parent.logit("EVR connected on server Socket Port " + evrPort);
            catch (Exception e)
              parent.logit("ERROR - Error accepting EVR connection: " + e.toString());
              killSocket = true;
            try
              reader = new BufferedReader(new InputStreamReader(
                  clientSock.getInputStream()));
              writer = new BufferedWriter(new OutputStreamWriter(
                  clientSock.getOutputStream()));
              parent.logit( "Created reader "+reader);
              parent.logit( "Created writer "+writer);
            catch (Exception e)
              parent.logit(
                  "ERROR - creating reader or writer to EVR: " + e.toString());
              killSocket = true;
          int nullCount = 0;
          while (killSocket == false)
            try
              parent.logit("Waiting for message from EVR..... ");
    //          sendMessage("Data Controller connected on port " + evrPort);
              String s = reader.readLine();
              parent.logit("EVR - Received message: " + s);
              if (s != null)
                parent.processEvrMessage( s);
              else
                sleep(1000);
                nullCount++;
                if (nullCount > 10)
                  parent.logit("Exceeded retry limit: ");
                  killSocket = true;
            catch (Exception ex)
              parent.logit("Error Reading from EVR: " + ex.toString());
              killSocket = true;
          parent.logit( "After while loop");
          evrConnected = false;
          try
            retryCount++;
            parent.logit("Closing EVR connection. ");
            reader.close();
            writer.close();
            clientSock.close();
            writer = null;
            reader = null;
            clientSock = null;
            try
              sleep(1000);
            catch (Exception ee)
              parent.logit("Error after sleep " + ee.toString());
          catch (Exception e)
            parent.logit("Error closing EVR server socket");
    //=============================================================================
    // Call this method to kill the client socket connection.
    //=============================================================================
       * Call this method to kill the client socket connection.
      public void killConnection()
        killSocket = true;
    //=============================================================================
    // Return RTM connected state
    //=============================================================================
       * Return RTM connected state
       * @return boolean - Returns true if RTM is connected to server, false if not.
      public boolean isRtmConnected()
        return evrConnected;
    //=============================================================================
    // Returns state of server socket.
    //=============================================================================
       * Returns state of server socket.
       * @return boolean - Returns true if server socket is enabled, false if not.
      public boolean isServerSocketAlive()
        return alive;
    //=============================================================================
    // Send a message to the client socket.
    //=============================================================================
         * Send a message to the client socket.
         * @param msg String - Message to send.
         * @return boolean - Returns true if message sent OK, false if not.
      public boolean sendMessage(String msg)
        parent.logit(" In EVR Server - Send Message - got message: " + msg);
        if (evrConnected)
          try
            parent.logit("Sending message to EVR: " + msg);
            writer.write(msg + "\n");
            writer.flush();
            return true;
          catch (Exception e)
            parent.logit("ERROR - Error sending message to EVR: " + e.toString());
            return false;
        else
          parent.logit("EVR not connected, cannot send message: " + msg);
          return false;
    }Client code:
    package evrsimulator;
    import java.net.*;
    import java.io.*;
    class PortConnector
          extends Thread
       ServerSocket serverSock = null;
       boolean isIP = false;
       InetAddress addr = null;
       Frame1 parent = null;
       byte[] rawIP;
        //   String initialMsg = "";
       public PortConnector( Frame1 f )
         parent = f;
       // This method is called when the thread runs
       public void run()
          if ( parent.hostName.indexOf( "." ) > 0 )
             isIP = true;
             byte[] rawIP = parent.getRawIP( parent.hostName );
          try
             System.out.println( "Connecting to host " +
                                            parent.hostName + " on port " +
                                            parent.socketPort );
             if ( isIP )
                addr = InetAddress.getByAddress( rawIP );
             else
                addr = InetAddress.getByName( parent.hostName );
             System.out.println( "Inet address = " + addr );
             SocketAddress sockaddr =
                   new InetSocketAddress( addr, parent.socketPort );
             // Create an unbound socket
             parent.client = new Socket();
             // This method will block no more than timeoutMs.
             // If the timeout occurs, SocketTimeoutException is thrown.
             parent.client.connect( sockaddr, parent.socketTimeOut );
             parent.socketOut =
                   new BufferedWriter( new OutputStreamWriter(
                   parent.client.getOutputStream() ) );
             parent.socketIn = new BufferedReader( new InputStreamReader(
                   parent.client.getInputStream() ) );
             parent.localName = parent.localName +
                   parent.client;
             System.out.println( "Parent socketOut = "+parent.socketOut);
             System.out.println( "Parent socketIn = "+parent.socketIn);
          catch ( UnknownHostException uhe )
             System.out.println( "Unknown Host - " + uhe.getMessage() );
          catch ( SocketTimeoutException ste )
             System.out.println( "Socket time out - " + ste.getMessage());
          catch ( IOException ioe )
             System.out.println( "IO exception - " + ioe.getMessage() );
          // Listen on socket for message from host - thread should block.
          parent.portConnected = true;
          while ( parent.portConnected )
             try
                String msg = parent.socketIn.readLine();
                System.out.println( "Message from Host: " + msg );
                System.out.println( "Message from Host: |" + msg + "|" );
                if( msg.length() > 2)parent.processMessage( msg );
             catch ( IOException ioe )
                System.out.println( "Exception creating server socket." );
          try
             System.out.println(
                   "PortConnection - Closing socket and IO connections" );
             parent.socketIn.close();
             parent.socketOut.close();
             parent.client.close();
             parent.clockRunning = false;
             if( parent.heartBeating) heartBeat.interrupt();
          catch ( IOException ioex )
             System.out.println( "Exception closing socket." );
    }

    Your first problem is that you keep closing and recreating the ServerSocket. Do this once only in the lifetime of the server.
    This is such a basic error that I haven't read the rest of the code. Before you go any further I suggest you read the Custom Networking trail of the Java Tutorial.

Maybe you are looking for

  • Valuation Method for Indian Payroll

    Hi, Can any one let me know the valuation method available in Indian Payroll. As per my knowledge is concern I Know there are 4 valuations methods are there. Can any one just provide me with name's of four valuation method. Thanks in Advance Irfan Hu

  • Not allowing to create field starting with underscore and numbers

    Hi All I'm trying to create a datatype in PI 7.1 with element starting with underscore and numbers like _Name , 1.0.Name. when I'm trying to activate the dataype. I'm getting the error Activation of the change list canceled.please help me out Thanks

  • Resource bundle in the task definition

    Hi all, I'm trying to assign my own resource bundle to a human task definition like specified in the developer doc (http://download-west.oracle.com/docs/cd/B31017_01/integrate.1013/b28981/workflow.htm#BABDFDHC). The documentation is not clear at all

  • HI pls help with Muse CC for backstretch jquerry :(

    greetings im harvey im having a problem on calling the background from backstretch heres my code on the html object ; <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="jquery.backstretch.min.js"></script>

  • Dreamweaver Sites - FTP - Testingserver to Remoteserver

    I'm working with a little team of web-developers (3 persons). We use a MacBook as an Apache-Webserver (PHP and MySQL). Our Client-Developer-Tool is Dreamweaver CS 6 on each of our notebooks. Now my question about Dreamweaver Sites: The MacBook is our