About Mikazo Tech Blog

My name is Mike, and this blog is my way of saving people time. If someone has a specific problem that I've encountered before, hopefully these posts will save them the extraneous Googling I had to go through to solve the same problem. Also, when I have something to say about technology today, I will post my thoughts here. If this blog has helped you out, even a little bit, vote on the poll below, or let me know by sending me an email. I'm always open to exchanging links with other blogs or websites that share a similar interest.

Friday, December 5, 2008

Common Java Socket Programming Bugs

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.

1 comments:

pbsl said...

you have a nice site. thanks for sharing this site. there are various kinds of ebooks are available here

http://feboook.blogspot.com

Donate to Mikazo Tech Blog