Reputation: 2473
I am unable to do any networking in Java when i run a simple networking program i am unable to get a connection, even when using the local host, The Error:
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 EchoClient.main(EchoClient.java:8)
This is the program:
import java.io.*;
import java.net.*;
import java.util.*;
public class EchoClient{
public static void main(String[] args) {
try{
Socket client = new Socket(InetAddress.getLocalHost(), 1234);
InputStream clientIn = client.getInputStream();
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut);
BufferedReader br = new BufferedReader(new InputStreamReader(clientIn));
Scanner stdIn = new Scanner(System.in);
System.out.println("Input Message:");
pw.println(stdIn.nextLine());
System.out.println("Recieved Message:");
System.out.println(br.readLine());
pw.close();
br.close();
client.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I use windows 7, i have turned of windows firewall and i dont have an anti virus.
Upvotes: 3
Views: 28558
Reputation: 11
My solution in Windows 7 was to turn on "Simple TCP/IP Services". It's described here: http://www.windowsnetworking.com/articles_tutorials/windows-7-simple-tcpip-services-what-how.html
Upvotes: 1
Reputation: 43504
As I wrote in my comment, check that the server (something like EchoServer?) is up and running.
But there are other problems when you succeed connecting. pw.println(stdIn.nextLine());
might not send the content to the server, you need to do a pw.flush();
to really send the content or you can create your PrintWriter
with autoflushing:
pw = new PrintWriter(clientOut, true);
If you need a EchoServer
I just wrote one that works with your client if you add the flushing that I described above:
public class EchoServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(1234);
while (true) {
// accept the connection
Socket s = ss.accept();
try {
Scanner in = new Scanner(s.getInputStream());
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
// read a line from the client and echo it back
String line;
while ((line = in.nextLine()) != null)
out.println(line);
} catch (Exception e) {
e.printStackTrace();
} finally {
s.close();
}
}
}
}
You can try it with telnet localhost 1234
.
Upvotes: 1
Reputation: 114817
Double check that your local EchoServer is up and running on port 1234. If there is no server operating on that port, you won't be able to connect.
Upvotes: 1