开发者

Java Server and Client - unable to construct InetAddress

I'm trying to write a server and client program in java. I've not done this before, so I figured I'ld start with the examples provided at the links below.

Server code: http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/Code/SocketServer.java

Client code: http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/Code/SocketClient.java

I made a few changes in terms of the naming, but the basic functionality should be the same. The server app runs fine, but the client app is throwing an UnknownHostException. I thought the problem was probably something to do with the IP address used in both apps not being valid. I'm running this on Mac, and I don't claim to be an expert on IP addresses, but I figured it might be a good idea to write code that would actually print out the IP address, which is posted below, in case it's at all helpful.

java.net.InetAddress address = ja开发者_开发知识库va.net.InetAddress.getLocalHost();
System.out.println("IP Address  :"+address.getHostAddress());

However, this code returns some number like 463.827.201.789(not really this but just for demonstrative purposes), which definitely doesn't work as a parameter of the Socket constructor I'm using.

Anyway, I don't know what the issue is and I need help here.


Printing the InetAddress objects getHostAddress() method prints a textual representation of the address (as specified in the API, check http://download.oracle.com/javase/6/docs/api/java/net/InetAddress.html#getHostAddress()). This should be the IP address of your computer? (Or possible 127.0.0.1, the address that always points to your local computer).

The Socket class (http://download.oracle.com/javase/6/docs/api/java/net/Socket.html) takes an InetAddress + port number in the constructor so you should be able to pass it the InetAddress and the first parameter and the port number that your SocketServer listens on. (Each server socket opens up a listener on a port number which you can basically choose yourself, check http://download.oracle.com/javase/6/docs/api/java/net/ServerSocket.html).


In the line

 socket = new Socket("kq6py", 4444);

what did you provide instead of "kq6py" ? Assuming your server program is running on the same computer as your client - you should try "localhost" or "127.0.0.1"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜