Problem with socket programming-connecting to port 13

Hi, I am learning JAVA, and we are on the subject of sockets. I am trying to make this program to connect to port 13, get the time, and print it to the console. This is my code:
import java.io.*;
import java.net.*;
public class temp {
     public static final int PORT = 13;
     public static void main(String[] args) {
          Socket s = null;
          String line = null;
          try {
               s = new Socket("localhost", PORT);
               DataInputStream sin = new DataInputStream(s.getInputStream());
               line = sin.readLine();
               if (line != null) System.out.println(line);
          catch (IOException e) {System.err.println("!" + e);}
          finally {
               try { if (s != null) s.close(); }
               catch (IOException e2) {}
And this is the output:
!java.net.ConnectException: Connection refused: connect
What should I do. I found that the problem is with the server I am connecting to and I tried connecting to dif. computers, or to stuff online, and nothing works.
Any suggestions for me?
Forgot: I tried this on both a windows XP and Vista
Edited by: xpatrickerx on Mar 23, 2008 8:12 PM
Tampering with it, I find that the error occurs on the following line:
s = new Socket("localhost", PORT);
Edited by: xpatrickerx on Mar 23, 2008 8:13 PM

So I finally found how to use printStackTrace and here is what it gives when:
1) I use my own computer:
java.net.ConnectException: Connection refused: connect
     at java.net.PlainSocketImpl.socketConnect(Native Method)
     at java.net.PlainSocketImpl.doConnect(Unknown Source)
     at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
     at java.net.PlainSocketImpl.connect(Unknown Source)
     at java.net.SocksSocketImpl.connect(Unknown Source)
     at java.net.Socket.connect(Unknown Source)
     at java.net.Socket.connect(Unknown Source)
     at java.net.Socket.<init>(Unknown Source)
     at java.net.Socket.<init>(Unknown Source)
     at temp.main(temp.java:11)
2) I use something else:
java.net.ConnectException: Connection timed out: connect
     at java.net.PlainSocketImpl.socketConnect(Native Method)
     at java.net.PlainSocketImpl.doConnect(Unknown Source)
     at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
     at java.net.PlainSocketImpl.connect(Unknown Source)
     at java.net.SocksSocketImpl.connect(Unknown Source)
     at java.net.Socket.connect(Unknown Source)
     at java.net.Socket.connect(Unknown Source)
     at java.net.Socket.<init>(Unknown Source)
     at java.net.Socket.<init>(Unknown Source)
     at temp.main(temp.java:11)
Again, thanks

Similar Messages

  • 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 Programming

    Hi
    I have used java sockets in my program for installing a tool on different boxes.On running this server program on a linux box my client program is unable to listen to the socket on the linux box.It give a
    ConnectionRefused exception in the client program which is running on the windows box.This behaviour is pretty inconsistent though.The version of linux is redhat 7.3 and the kernel is 2.4.18-3 on au i686 (valhalla) and the java version on the
    linux ->1.4.0_01-b03,mixed mode.
    The windows box also has j2sdk1.4.0.
    Please reply urgently.

    I have used the same source to open sockets on windows and on solaris and it has worked consistenly.It is only the linux box that is inconsistent in listening to the sockets.
    On the server i have used this part to open the socket:
    public void process() throws Exception {
              SocketChannel sc = null;
              ServerSocketChannel ssc = null;
              Selector acceptSelector = null;
              try {
                   int port = Integer.parseInt(resourceBundle.getString("AUTH_PORT"));
                   System.out.println("Listening on Port:: "+port);
                   int socketTimeOut = Integer.parseInt(resourceBundle.getString("SOCKET_TIMEOUT"));
                   acceptSelector = SelectorProvider.provider().openSelector();
                   ssc = ServerSocketChannel.open();
                   ssc.configureBlocking(false);
                   InetAddress lh = InetAddress.getLocalHost();
                   InetSocketAddress isa = new InetSocketAddress(lh, port);
                   ssc.socket().bind(isa);
                   SelectionKey acceptKey = ssc.register(acceptSelector,SelectionKey.OP_ACCEPT);
                   int keysAdded = 0;
                   while ((keysAdded = acceptSelector.select()) > 0) {
                        // Someone is ready for I/O, get the ready keys
                        Set readyKeys = acceptSelector.selectedKeys();
                        Iterator i = readyKeys.iterator();
                        // Walk through the ready keys collection and process date requests.
                        while (i.hasNext()) {
                             boolean processFlag = true;
                             SelectionKey sk = (SelectionKey)i.next();
                             i.remove();
                             // The key indexes into the selector so you
                             // can retrieve the socket that's ready for I/O
                             ServerSocketChannel nextReady = (ServerSocketChannel)sk.channel();
                             // Accept the date request and send back the date string
                             sc = nextReady.accept();
                             so = sc.socket();
                             writeToLogFile ("Socket is ::"+so+"::",4);
    //                         so.setSoTimeout(socketTimeOut);
                             writeToLogFile ("Before receiveAuthReqMessage",4);
                             ois = new ObjectInputStream(so.getInputStream());
                             receiveAuthReqMessage();     // receive AuthReqMessage.xml
                             writeToLogFile ("After receiveAuthReqMessage::"+processFlag,4);
    //                         readAuthReqMessageData();     // reads the userName, password for validation
                             authenticate();                    // validates username & password of client
                             sendAuthResMessage();          // feedback to client AuthResMessage.xml
                             if(validbool)
                                  while (processFlag) {
                                       processFlag = receiveRegReqMessage();
                             else
                                  writeToLogFile ("INVALID : You are NOT a VALID user .......",0);
                             writeToLogFile ("Just before closing",4);
                             ois.close();
    //                         sc.close();
    //                         so.close();
              } catch (Exception e) {
              e.printStackTrace();
              finally {
                   os.close();
                   sc.close();
                   ssc.close();
                   acceptSelector.close();
                   so.close();
    and on the client part of the program i use this code to make the client listen to the server program:
         public boolean openAuthSocket(String machineName) {
              try{
                   int portNo = 0;
                   ResourceBundle resourceBundle = ResourceBundle.getBundle("GPSClientProperties", locale);
                        portNo = Integer.parseInt(resourceBundle.getString("AUTH_PORT"));
                   if (machineName == null) {
                        machineName = resourceBundle.getString("AUTH_MACHNAME");
                   authsocket =new Socket(machineName,portNo);
                   writeToLogFile("Authentication socket OPENED on authsocket: " +authsocket,4);
                   int socketTimeOut = Integer.parseInt(resourceBundle.getString("SOCKET_TIMEOUT"));
                   authsocket.setSoTimeout(socketTimeOut);
              }catch (Exception e){
                   writeToLogFile("The exception in open socket is "+e,0);
    e.printStackTrace();
                   return false;
              return true;

  • Firefox does not know how to open this address because the protocol (Sims3) with any program connects

    Firefox does not know how to open this address because the protocol (Sims3) with any program connects
    can you help me plz

    Was the message sent from Microsoft Outlook? When you embed an image in a message in Outlook (at least up to version 2003), it creates a hidden attachment for the image and then inserts a "cid" reference to it. If the attachment gets stripped for any reason then the "cid" reference is useless: Outlook does not store the original URL or path to the image.
    Edit: By the way, which webmail site has this problem?

  • Problem with my internet connection and modem

    hello!
    i have a very big problem with my internet connection a 56k. i use internet with my internal apple modem (i have an ibook g4). sometimes it works well but sometimes, after being connected, my ibook freezes and i have a black window wich says: "you need to restart your computer".
    i do it, and when i want to connect again, i have a new message wich says " this port of communication does'nt exist. please check your setup and do it again" (in french) i check my preferences in the "preferences" and the modem doesn't appear!! see it my photos here (in french sorry):
    http://h1.ripway.com/diesel/pdf.pdf
    in order to use internet normally, i'm obliged to re-install tiger again and again!! i'm very hungry about this problem because since i'have my connection, i can"t use it as i want!
    please help me!

    Hi David,
    What you've described is a kernel panic. Since reinstalling the OS only alleviates the issue temporarily it's possible that your modem is failing.
    Jrsy

  • Problems with n97 apps connecting to network (Voda...

    Problems with n97 apps connecting to network (Vodafone UK – 3G)
    Recently a number of my apps which used to connect automatically to the internet (which ever was available – known wi-fi or 3g) have stopped doing this.  They now only connect to one known wi-fi.
    I’ve tried uninstalling and reinstalling each app, but this hasn’t solved the problem.  I’ve checked for software updates and do not believe any have been applied or are available.  All apps have been downloaded via Ovi on the phone.  I still am able to access the internet by the web browser which was installed on the phone and via google maps (which also still manages GPS position, search, etc).
    The apps which I notice causing a problem are:
    Sainsbury’s/nectar
    Tesco
    Map my tracks
    Snaptu
    Opera Mini
    Any one got any ideas???

    I have the same problem since i updated my mac to 10.5.6.
    Each time I have to do a diagnostic and retype the WEP password to have the internet connection.

  • I am having problems with the wifi connection on my ipad 4th generation only 3 weeks old. Have left it back to the shop i bought it in and they said they have to send it away now i am left with no ipad. What after sales support do you give really?

    Does anyone else have problems with the wifi connection on their 4th generation  Mine keeps going off line and its only 3 weeks old.I had the ipad mini and this problem never existed. I brought it back to the shop where i bought it Expert Laois last week and they said they couldnt find a problem but had to take it back today as it keeps disconneting from wifi still, anyway they are sending it back for repair and it am left with no ipad.  After spending in excess of 700e i feel that this is really bad after sales service.  I bought something that i want to use now and cant so what  a waste of money it is .

    Thankyou, but the shop said that they spoken to apple and that they have now changed their policy and that they do not give a replacement.  So are you telling me that their information is false.  Also what should they have done.  This problem has existed since i bought it.?????  What should i do?????

  • Both xp and windows 7 have video problems with my VGA connection using TV

    both xp and windows 7 have video problems with my VGA connection using TV as my monitor when it gets to starting up windows no matter what version it will not I have let my mac on all night and still says starting windows or the windows 7 logo and nothing else will happen also when I use a 3rd patty software like peraills or other it works like a charm how to fix it?

    To map the drive on your computer click on Start - RUN - type "\\192.168.1.1" and click ok... When prompted for Username and Password type "admin" and click ok... Now you will be able to see the folder which you have shared on  your router, right click on it and select "Map network drive" and click on finish.
    Now it will map the drive on your computer and you should be able to transfer the file from your computer to the USB drive.

  • Hi, recently purchased macbook 13", I have problem with sound when connect to my LG Smart tv with sound system. When i change sounds effect on my sound system also LG its all go quiet didn't have this problem with my laptop. Any advise ?

    Hi, recently purchased macbook 13", I have problem with sound when connect to my LG Smart tv with sound system. When i change sounds effect on my sound system also LG its all go quiet didn't have this problem with my laptop. Any advise ?

    Some progess I see. To be honest, i would not waste your time with trying to connect using wireless.
    You are likely to get poor connections and dropping out.
    If its working using a cable, then there is no need to bother with giving me the network settings, bu see how it goes, because sometimes giving the TV a static IP address can give better results.
    There is an example of a couple of powerline adapters on the diagram below. Just ignore the network switch unless you want to connect other devices which are near to the TV.
    http://forumhelp.dyndns.info/networking/powerline3.jpg
    I will monitor the subject line of this thread, should you want to post any more information.
    There are some useful help pages here, for BT Broadband customers only, on my personal website.
    BT Broadband customers - help with broadband, WiFi, networking, e-mail and phones.

  • Language problem with my jdbc connection

    Hello,
    i'm having a problem with my jdbc connection.
    the problem is that i'm connecting to MS- Access db the have arabic tables, and columns, it was working fine on a windows XP environment prepared for arabic language, but when i had to move to windows vista it did not work and it gave me an exception.
    i'm using netbeans 6.1 IDE, and the exception is
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect
    at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
    at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
    at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3110)
    at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:338)
    when i printed the select statement and the exception it gave me:
    SELECT [??? ???????], [??? ??????], [??? ?????], [??? ?????], [????? ???????????] FROM EDU_DIVISION; [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect.
    the question marks are very weird to appear!!!!!!
    here is the code:
    public void edu_branch() {
            sucpy = 0;
            eflag = 0;
            asql = "SELECT [\u0643\u0648\u062F \u0627\u0644\u062C\u0627\u0645\u0639\u0629], [\u0643\u0648\u062F \u0627\u0644\u0643\u0644\u064A\u0629], [\u0643\u0648\u062F \u0627\u0644\u0642\u0633\u0645], [\u0643\u0648\u062F \u0627\u0644\u0634\u0639\u0628\u0629], [\u0627\u0633\u0645 \u0627\u0644\u0634\u0639\u0628\u0629], [\u0627\u0633\u0645 \u0627\u0644\u0634\u0639\u0628\u0629 \u0628\u0627\u0644\u0627\u0646\u062C\u0644\u064A\u0632\u064A\u0629], [\u0627\u0644\u0643\u0648\u062F \u0627\u0644\u0645\u062E\u062A\u0635\u0631] FROM EDU_BRANCH;";
            Connection connection;
            Statement statement;
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                connection = DriverManager.getConnection("jdbc:odbc:info");
                System.out.println("Connection to Access file is created...");
                statement = connection.createStatement();
                statement.execute(asql);
                System.out.println("Executing query : " + asql);
                aset = statement.getResultSet();
                if (aset != null) {
    //------------------------------Oracle operations--------------------------------------------------------------------                  
                    while (aset.next()) {
        can you help me please

    arabic language
    SELECT [??? ???????], [??? ??????], [??? ?????], [??? ?????], [????? ???????????] FROM EDU_DIVISION; >[Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect.
    the question marks are very weird to appear!!!!!!It failed to understand your unicode sql.
    it was working fine on a windows XP environment prepared for arabic language, but when i had to move to windows vista it did not workStrange. Maybe you need to compare the differences of some system properties on both hosts, for instance, sun.io.unicode.encoding, file.encoding, user.region, and so on.

  • Has Apple fixed the problem with 4G cellular connection?

    Has Apple fixed the problem with 4G cellular connection on the iPad 3?

    Cellular connection problem was for US connection in Houston, Texas.  Have an iPad 2 which functions perfectely on Wi-Fi or 3G.  Bought an iPad 3 strictly to get the increased speed from the 4G LTE connection.  Purchased on with the AT &T cellular.  Wi-Fi functions fine, but 4G LTE connection is terrible when it connects at all.  Went to AT&T and they said no problems with service in my area, but never get over 2 bars and most times, Web pages load very slow or will hang and not load at all.  Went to the Apple store and they said it was AT&T network problem and went to AT&T and they said no problems with their service.  Went to the Apple communities forum here and discovered that many people were having the same problems with the 4G LTE cellular connection on their iPad 3's.  Didn't seem to matter if it was AT&T or Verizon.  So I decided that I would just return the unit and wait for Apple to fix the problem.  Hence my question.
    Appreciate very much your time in responding to my question.

  • Problem with the program symbols in quality

    Dear all,
    I am facing a problem with the program symbols.
    I have added new global fields in development, i have called those definations in text names. It is working fine.
    After transporting these  program changes in to quality these new global definations are not displaying in quality and varibles are not working.
    Please give me some suggestion.
    Thanks and advance

    Hi Chandra,
    Please check the following.....
    (1)The transport request status in se10 and see if has been successfully imported to QA..
    (2)if all the declarations or code have been collected in a Transport and not saved as temporary objects
    To confirm the same we have to compare the code in quality and development and see if they are the same
    Pls check and revert
    Regards
    Byju

  • Organizer elements 11.  Problem with your internet connection

    I am trying to access facebook and Flickr via the Organizer with elements 11.  I went to preferences and cleared the oline services, when I try to refresh the partner services I am greeted with the error " there is a problem with your internet connection, check your firewall settings" .
    Windows 8, updated.  I tried disabling the firewall.  I have also tried making sure permissions are set up to allow all adobe products access through the frewall when it is enabled.   No other network managment services or virus scanners installed.  just default 64bit windows 8.
    I am currently left with no partner services; facebook, flicker, picasa, etc....   I could reinstall organizer i guess to get the default services back...
    I found discussions on the web but none with a solution. http://forums.adobe.com/message/4035670
    Any help would be great

    I apologize for the delay.  An update was released shortly after I posted the question that resolved the issue.  Thank you for your assistance though.  As soon as I read your advice I went to my laptop to follow your instructions.  Upon opening photoshop I was prompted with an adobe update message.  After the update the issue was resolved.  Again, sorry for not updating the situation.

  • I'm having problems with my internet connection after installing OS X Lion. Is this a known problem or just a local problem?

    I'm having problems with my internet connection after installing OS X Lion. Is this a known problem or just a local problem?
    After +/- 10 to 15min my connection is gone.
    Does anyone have a sollution?

    Lots of people are having the same problem, you're not the only one, belieeeeve me.
    Just Googling the problem gets you tons of people complaining about the same thing, SOMETHING is up with Lion what wasn't happening with Snow Leopard. i just bought a new Imac and it CAME with Lion, so i started experiencing this internet dropout immediately.
    It's been going on for the most of a year it looks like (at least by the dates from the threads i've been reading)
    So your best bet is to fiddle with the System Preferences and read what other people have used to make theirs work. i'm doing that myself right now.  I already posted  a similar thread last night trying to figure out why my connection kept on dropping, i got a reply which linked me to a site. i followed the instructions there, so far so good, but i'm just being cautiously optimistic.
    i'm gonna call Apple today and see if they've found anything, though seeing as this is a problem right out of the box there may not be an immediate solution. Good luck hunting for a solution :3
    Site:
    http://osxdaily.com/2011/11/06/lion-wi-fi-problems-solution-mac/?utm_source=feed burner&utm_medium=feed&utm_campaign=Feed%3A+osxdaily+%28OS+X+Daily%29&utm_conten t=FaceBook

  • I installed Adobe CS6 Design & Web Premium on my Mac Book Pro a few years ago but have repeatedly encountered problems with the programs freezing or not opening properly. It's a Student and Teacher Licensing version so an academic ID is required but I am

    I installed Adobe CS6 Design & Web Premium on my Mac Book Pro a few years ago but have repeatedly encountered problems with the programs freezing or not opening properly. It's a Student and Teacher Licensing version so an academic ID is required but I am no longer a student--can I still reinstall it since my academic ID may no longer be valid?

    Erin Elzo as long as the serial number has been registered under your account at http://www.adobe.com/ then you should be able to continue to utilize the software.  You can find details on how to locate your registered serial number at Find your serial number quickly - http://helpx.adobe.com/x-productkb/global/find-serial-number.html.

Maybe you are looking for

  • Create Client Installer Failing

    I have a brand new Mac Mini running Apple Remote Desktop 3.5.1 on Lion 10.7.3 that I am trying to create a custom client installer and right at the end it fails every single time. Saying that "An unexpected error has occured while creating a custom i

  • Lightroom cc screen blanks while editing

    Just trialling LR CC and I find that using editing tools like the adjustment brush, that the screen blanks after each application of the brush and sometimes the adjustment doesn't happen. I never experienced this with 5.7 My system is OS X 10.10.3 on

  • Position syncing with iCloud and non-store ePubs

    Since the iCloud beta became available, iBooks now remembers which page you're on accross all your IOS devices - so I can start reading a book on my iPad, then switch over to my iPhone later on and it will pick up where I left off. This seems to work

  • Exchange Portlet problem

    hi experts, we have a problem getting the asp pages that come with the exchange portlet running. The inbox.asp script runs fine, when not the contacts.asp and calendar.asp, they both come back with the error message that the the method 'GetDefaultFol

  • Purchase Help: iMac 2011 vs Thunderbolt Display   Mac Mini 2011

    Hello, I purchased Thunderbolt display with Mac mini 2011. I experienced a lot of graphic issues with Mac mini when I connected to Thunderbolt display. I exchanged Mac mini 3 times but the same result. The Thunderbolt display is working fine with Mac