PDA

View Full Version : Networking confusion


DELOCH
11-25-2008, 02:27 AM
codes:
SimpleClient.java:

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

public class SimpleClient
{
public static void main(String[] args)
{
Socket sock = null;
PrintWriter out = null;
Scanner in = null;

System.out.println("Teh 1337 Clientz ist onlinz!");
try {
sock = new Socket("localhost", 1234);
out = new PrintWriter(sock.getOutputStream());
in = new Scanner(sock.getInputStream());

out.print("get");
String quote = in.nextLine();
System.out.println(quote);
out.println("bye");
} catch (Exception e) { }
}
}

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

public class SimpleServer
{
public static void main(String[] args)
{
ServerSocket ss = null;
Socket sock = null;
PrintWriter out = null;
Scanner in = null;

System.out.println("Teh 1337 Systemz r onlinz!");
try {
ss = new ServerSocket(1234);
sock = ss.accept();
System.out.println("Connection set for: " + sock);
out = new PrintWriter(sock.getOutputStream());
in = new Scanner(sock.getInputStream());

while (true) {
String s = in.nextLine();
if (s == "bye") {
break;
} else if (s == "get") {
out.println("Random number: " + (Math.random() * 400));
} else {
out.println("Whaddja want frum mi!");
}
}
sock.close();
ss.close();
} catch (Exception e){};
}
}


The server is made to respond to request "get" -- give random message
The client is made to get that response and print it to console
The client is never getting that response... :|

shyam
11-26-2008, 04:09 PM
thats coz the communication is buffered and as long as you don't exceed the buffer the data will not be transferred...you have to call flush() on your output streams to immediately transfer the data

DELOCH
11-26-2008, 08:42 PM
I called .flush() explicitly but nothing changed.
my output stream performs autoflush anyway... :|

nothing changed... still doesn't work

shyam
11-28-2008, 02:32 AM
I called .flush() explicitly but nothing changed
assuming you changed the prints to printlns (readLine expects a newline char before returning :cool:) and fixed

if (s == "bye") {
break;
} else if (s == "get") {
out.println("Random number: " + (Math.random() * 400));
} else {
out.println("Whaddja want frum mi!");
}
that it ain't gonna work..

my output stream performs autoflush anyway... :|
really? take a look here (http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.OutputStream))