I was trying to create a socket object using the following code:
But when i run the compiled bytecode (class file) the machine throws an exception with the following stack trace: 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 ChatServer.main(ChatServer.java:9)
I am running this on a machine that runs the 'Windows Vista Starter' edition. The jvm version number is 1.5.0_15.
I even tried running the above code after disabling both the windows firewall and Norton Antivirus's firewall. But to no avail.
You need a server/service/daemon bound to a port in order to connect a socket to it. Since the name of your class is "ChatServer", I think you are trying to bind to a port in order to receive connections. You do this by creating an instance of ServerSocket. Have a look at the Java Tutorial on Custom Networking. A little study beforehand will save you a lot of grief down the road.
Your suggestion worked! I was not aware that I had to start a server at the specified port before I could even instantiate a Socket object :-). Here's what I did after I saw your reply.
1. I changed the code of the class ChatServer to this
2. I wrote a small piece of code that would play the client:
Then I opened a terminal and made the jvm execute the bytecode for 'ChatServer' class. I opened another terminal and invoked jvm to execute the bytecode for 'ChatClient' class. And I met with 'Success!'.
Of course the program doesn't do anything useful. But I always start exploring by starting in a small way. I will now build on the above code so that it will do something more useful.