Server Code
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author efron
*/
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(Integer.parseInt("49999"));
System.out.println(serverSocket.getLocalPort());
while (true) {
System.out.println("Waiting for Client...(port = " + 49999 + ")");
Socket acceptSocket = serverSocket.accept();
System.out.println("Connected to: " + acceptSocket.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(acceptSocket.getInputStream());
DataOutputStream out = new DataOutputStream(acceptSocket.getOutputStream());
System.out.println(in.readUTF());
out.writeUTF("You have been connected to the server" + acceptSocket.getLocalSocketAddress());
acceptSocket.close();
}
} catch (Exception e) {
}
}
}
Client Code
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
/**
*
* @author efron
*/
public class Client {
public static void main(String[] args){
//If I put localhost or 127.0.0.1 as the servername, it works
String serverName = "123.123.123.123"; //put my own ip address in servername, got it from http://www.whatismyip.com/
int portNumber = Integer.parseInt("49999");
try {
System.out.println("Connecting to server " + serverName + " on port " + portNumber);
Socket client = new Socket(InetAddress.getByName(serverName), portNumber);
System.out.println("Connected to server!");
DataInputStream in = new DataInputStream(client.getInputStream());
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeUTF("Hi Server! I'm " + client.getLocalSocketAddress());
System.out.println("Message from Server: " + in.readUTF());
client.close();
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
}
I run the server, and the server will be waiting at port 49999.
Then I run the client. But the Client gives an IOException, Connection refused.
Can anybody tell me whats wrong.
I asked somebody to do the same thing that I do here(I give him my code and ask him to run it) with Ubuntu 10.10 and it works just fine, but in my Ubuntu 11.10, I keep trying various ways to write the code that means the same thing a thousand times and it still doesnt work.
Can anybody think of how this might have happened?
Please help. Thanks
P.S. The ip address is changed to 123.123.123.123 but when I run it its my ip address. And when my friend run it its his ip address