Last year I wrote an internet chat client in Java, and just now I've decided to write a file transfer program in Java. Both of these programs taught me how to use the Socket class from the Java API. I've ran into a few programming mistakes that cost me a lot of time, so here are some things to watch out for.
Remember that InetAddress.getHostAddress(); returns a string of the form "hostname/x.x.x.x" so to get just the IP address string you might want to do something like InetAddress.getHostAddress().split("/")[0];
When you are doing
Socket clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
out.print("Hello World!");
Be careful how you read on the other end with
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
in.readLine();
The .readLine() method looks for a line break at the end of the string, but when you are using out.print() no "\n" is added to the end. Use out.println(); instead.
Lastly, if you are sending text such as out.println(); remember that it is not actually sent until you call out.flush();
Hopefully these tips will save you a bit of grief if you are new to network programming with Java. I know I would have been grateful if someone had told me about these simple things.
Friday, December 5, 2008
Subscribe to:
Post Comments (Atom)





1 comments:
you have a nice site. thanks for sharing this site. there are various kinds of ebooks are available here
http://feboook.blogspot.com
Post a Comment