Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Head First Client Server Example

 
Karen Baog
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a ready-baked code from the Head First Java book, for the Server and Client codes.
The problem I am having is trying to get the client to send a test message, and then receive it back.
I can't get it to work.
I have added a few lines to the client code to send the test message.
Where have I gone wrong?

When I run it, the server accepts the client connection. But it doesn't print the test message the client sends. It seems it hasn't received it.
So, I don't know if the client has really sent the message. If it did, I don't know why the server failed to read and print it.

This is the Server code, instead of me just referring you guys to the book. If the code is too long, I apologize in advance. The client code is also below.




This is the simple client code. Again, from the Head First Java.





Thanks in advance!
Karen
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your server is stuck trying to read a line. Instead of sending "Hello" from the client, send "Hello\n", and it will work.
 
Satish Talim
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Karen Baog:

public void go()
{
clientOutputStreams = new ArrayList();
try
{
ServerSocket serverSock = new ServerSocket(portNo);

while(true)
{
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());

System.out.println(writer.toString());

Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection on " + clientSocket.getPort());
}

}
catch(Exception e)
{
e.printStackTrace();
}
}

[/CODE]
Thanks in advance!
Karen


You have missed out the statement
[code]
clientOutputStreams.add(writer);
[/code]
after the [code]PrintWriter writer =[/code] statement.
 
Karen Baog
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for both responses.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!