Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Echo server not echoing correctly

Status
Not open for further replies.

lhtimbo

Programmer
Sep 15, 2005
3
US
This is an echo server that can handle multiple threads, but it doesn't work correctly. The problem is in the echo, only every other line is echoed back and forth and I am not sure why. Any suggestions? Thanks.

Code:
// Server that handles multiple threads.
import java.io.*;
import java.net.*;

public class Server {
	 static final int PORT = 10000;
	 public static void main(String[] args) throws IOException {
	   ServerSocket s = new ServerSocket(PORT);
	   System.out.println("Server Started");
	   try {
	     while(true) {
	       // Blocks until a connection occurs:
	       Socket socket = s.accept();
	       try {
	         new ThreadServer(socket);
	       } catch(IOException e) {
	        // If it fails, close the socket, otherwise the thread will close it:
	        socket.close();
	      }
	    }
	   } finally {
	      s.close();
	    }
	 }
}

// Server uses multithreading to handle any number of clients.
import java.io.*;
import java.net.*;

class ThreadServer extends Thread {
  private Socket socket;
  private BufferedReader in;
  private PrintWriter out;
  public ThreadServer(Socket s) throws IOException {
    socket = s;
    in =
      new BufferedReader(
        new InputStreamReader(
          socket.getInputStream()));
    // Enable auto-flush:
    out =
      new PrintWriter(
        new BufferedWriter(
          new OutputStreamWriter(
            socket.getOutputStream())), true);
    start(); // Calls run()
  }
  public void run() {
    try {
      while (true) {
        String str = in.readLine();
        if (str.equals("END")) break;
        System.out.println("Echoing: " + str);
        out.println(str);
      }

      System.out.println("closing...");

    } catch (IOException e) {
    } finally {
      try {
        socket.close();
      } catch(IOException e) {}
    }
  }
}

import java.net.*;
import java.io.*;

public class Client {
  public static void main(String[] args) throws IOException {
    InetAddress ip = InetAddress.getByName("localhost");
    System.out.println("addr = " + ip);
    Socket socket = new Socket(ip, 10000);
    try {
      BufferedReader in = new BufferedReader(
    		  				 new InputStreamReader(
    		  					 System.in));
      // Output is automatically flushed by PrintWriter:
      PrintWriter out =
        new PrintWriter(
          new BufferedWriter(
            new OutputStreamWriter(
              socket.getOutputStream())),true);

	String userInput;
	while ((userInput = in.readLine()) != null) {
	    out.println(userInput);
	    System.out.println("echo: " + in.readLine());
	}
    } finally {
      System.out.println("closing...");
      socket.close();
    }
  }
}
 
Change :

System.out.println("echo: " + in.readLine());

to :

System.out.println("echo: " + userInput);

The extra in.readLine() is blocking till you hit enter again (which send the \n char) ...

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
I'm having the exact same problems as he is except my client is done in flash.

When I send a message, I don't receive it back until another message is sent.

Please let me know if something is wrong with my server... Or if you catch a mistake in my actionscript. Thanks

import java.io.*;
import java.net.*;
import java.util.*;

public class Server
{
static protected Set activeClients = new HashSet();

public static void main(String[] args)
{
try
{
//makes new socket on port 9999
ServerSocket s = new ServerSocket(9999);
while(true)
{
//accepts incoming connections
Socket incoming = s.accept();
//creates new client handler for incoming connection
ClientHandler newClient = new ClientHandler(incoming);
//adds the new client
activeClients.add(newClient);
//starts the new client
newClient.start();
}
}
catch(Exception e)
{}
}
}



import java.io.*;
import java.net.*;
import java.util.*;

public class ClientHandler extends Thread
{
protected Socket incoming;
protected BufferedReader in;
protected PrintWriter out;

//send message function
public synchronized void sendMessage(String msg)
{
if(out != null)
{
//writes message to outgoing buffer/flushes
out.println(msg);
}
}

public ClientHandler(Socket incoming)
{
//initializes this.incoming
this.incoming = incoming;

try
{
if(incoming != null)
{
in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
//auto flush out-buffer
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(incoming.getOutputStream())), true);
}
}
catch(Exception e){}
}

public void run()
{
if(in != null && out != null)
{
try
{
while(true)
{
//receives line from client
String str = in.readLine();
if(str == null)
{
break;
}
else
{
//sends message back to client
sendMessage("Echo: " + str);
if(str.trim().equals("EXIT"))
{
break;
}
else
{
//gets client list from Server
Iterator iter = Server.activeClients.iterator();
//relays message back to all clients connected on server
while(iter.hasNext())
{
ClientHandler t = (ClientHandler) iter.next();
if(t != this)
t.sendMessage(str);
}
}
}
}
incoming.close();
Server.activeClients.remove(this);
}
catch(Exception e){}
}
}
}


///////////////////////////////////////////////////////////
//Flash Actionscript

//declare a new XMLSocket variables
var socket = new XMLSocket()

socket.onConnect = function(success)
{
//if connection is successful
if(success)
//goto and stop on chat frame
gotoAndStop(3);
else
//go back and stop on log on frame
gotoAndStop(1);
}

socket.onClose = function()
{
//if server is stopped go back to log on frame
gotoAndStop(1);
}

//when data is received through the socket
XMLSocket.prototype.onData = function(msg)
{
//display it in the text box
_root.display.text += msg;
//scroll the text box
_root.display.scroll += 10;
}

//send message function
function sendMessage()
{
//checks if user wants to quit
if(_root.message.text != "EXIT")
{
//sends message to server
socket.send(_root.name + ": " + _root.message.text + "\n");
//resets input box
_root.message.text = "";
}
else
{
//sends quit message to server
socket.send(_root.message.text + "\n");
//clears message box
_root.message.text = "";
}
}
//connects to host on port 9999
socket.connect(_root.ip, 9999)
 
Learn to debug - you need to assert whether the problem is your server, or your client.

So take the java client example posted above, and run against your server - if that works, then you know it is your "actionscript" client - if it fails, then you know it is your server.

Use the code posted above (with the modification I suggested) as a yardstick.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Actually I did debug, the server receives the message... Puts it into the buffer and is flushed, but the flash client receives nothing. Only when the next message is sent and flushed does it receive the last message sent to the buffer. I don't know whether its a flushing problem or my flash client.
 
I think you may have misdiagnosed the problem - there seems to be nothing wrong with the server.

See the below telnet session, proving all is well with the server.

Code:
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.localdomain.
Escape character is '^]'.
hello
Echo: hello
hello there
Echo: hello there
Connection closed by foreign host.

Also, a word of advice on checking if objects are null - you do a lot of it. While you should always check that critical objects have been created/initialized, I think you have slight overkill, especially on the "sendMessage" class - you already know it is not null as you checked it before.

The general rule of thumb is : set up the object - check its not null. If it is exit/throw an excepion or whatever. But don't double-check if objects are null when you have already checked them - this is just slowing your code down.

As for the flash problem, I don't know flash, so I suggest you ask on the appropriate forum.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top