Hey i am quite new to network programming
so i picked some example code from my books but i get always errors :s
I have a small client and server class
but when i want to make a new clientsocket with a addess and port i get an connection refused error
i can create a serversocket but when i ask a socket of it (by usijng accept) i get a cannot except error
i am behind a router but the port i work on is open so i cant seem to find the solution
any help?
my code:
import java.net.;;
import java.io.;
public class TestClient {
public TestClient() throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket(InetAddress.getLocalHost(), 4444);
System.out.println("Connected with server "
+ socket.getInetAddress() + ":" + socket.getPort());
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host.");
System.exit(1);
} catch (Exception e) {
System.err
.println("Couldn't get I/O for the connection to.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
import java.net.Socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.InetAddress;
public class TestServer {
public TestServer() throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println(“Could not listen on port: 4444.”);
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
clientSocket.close();
serverSocket.close();
}
}