tags:

views:

299

answers:

3

I'm trying to write a simple server-client program, but I have a problem: I can send data from client to server, but I can't send data from the server (I can't recive it in the client) :(
So how to send data from the server, and recive it in the client?

Server:

//this is in a thread
try {
    server = new ServerSocket(1365);
} catch (IOException e) {
    e.printStackTrace();
}
while (!exit) {
    try {
     clientSocket = server.accept();
     is = new DataInputStream(clientSocket.getInputStream());
     os = new PrintStream(clientSocket.getOutputStream());
     while ((line = is.readLine()) != null) {
      System.out.println("Message from client: " + line);
      //if (line.equals("exit")) {
      // exit = true;
      //}
      if (line.equals("say something")) {
       os.write("something".getBytes());
      }
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
    try {
     is.close();
    } catch (IOException ex) {
     ex.printStackTrace();
    }
os.close();
}

Client:

try {
    socket = new Socket(host, 1365);
    os = new DataOutputStream(socket.getOutputStream());
    is = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {}
if (socket != null && os != null && is != null) {
    try {
     os.writeBytes("say something");
     //get the answer from server
     os.close();
     is.close();
     socket.close();
    } catch (IOException e) {}
}

(sorry for the long code)
Thank you in advance.

+7  A: 

Your server's OutputStream is a PrintStream, but your client's InputStream is a DataInputStream. Try changing the server to use a DataOutputStream like your client.

Even better might be to change both to use PrintWriter and BufferedReader, like the example client/server pair in Sun's Socket Tutorial.


Just to explain a little about why your code didn't work: You can think of Stream objects as filters that your data passes through. The filter changes your data, formatting it so that the matching filter at the other end can understand it. When you send data through one type of OutputStream, you should receive it at the other end with the matching InputStream.

Just as you can't store a String object in a double, or a double in a String (not without converting it), you can't send data from one type of OutputStream (in this case a PrintStream) to a different type of InputStream.

Bill the Lizard
The program "freezed", but I read Sun's Socket Tutorial and now it's working! :)
Jani
Great, I'm glad it helped. Those are some of the best programming tutorials on the 'Net (not just the Socket Tutorials, but all of Sun's Java tutorials in general).
Bill the Lizard
A: 

I think an other problem was that I didn't send "\n" after the text, but I used readLine() method.

Jani
A: 

After your os.write() do os.flush(); the message is very small and maybe it's not being sent because it didn't fill the buffer.

Chochos