1

I recently programmed a simple Java server, and a client to test the server. The server is supposed to receive messages from the client, and send a random substring of the message back. The problem is this: When I send the message using the client program, the server does not respond. Then, when I kill the client program, the server leaps into action, and attempts to send the data back to the client. The server reads the data correctly but starts processing it only when I stop the client program.

This is the client code:

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

class ServerTest{

public static void main(String args[]) throws Exception{

    Socket clientSocket = new Socket(myIpAdress, 8001);

    //Send the message to the server
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

    String sendMessage = "randSubstring:StackOverflowIsAwsome";

    bw.write(sendMessage);
    bw.flush();
    System.out.println("Message sent: "+sendMessage);


    String message = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())).readLine();

    System.out.println("Message received from the server : " +message);

    clientSocket.close();

    }

}

My server code consists of two classes. This one is the listener:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerListener {
public static void main(String args[]) throws Exception {
    String clientSentence;
    ServerSocket socket = new ServerSocket(8001);

    while(true) {
        Socket connectionSocket = socket.accept();
        BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        //DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
        clientSentence = input.readLine();

        if(clientSentence.startsWith("randSubstring:")){

            Thread connection = new Thread(new ServerConnection(connectionSocket, clientSentence));
            connection.start();
        }

        Thread.sleep(300);
    }

}
}

This is the thread that will not start until the client is stopped:

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Random;

public class ServerConnection implements Runnable{

private Socket serverConnection;
private String sentence;

public ServerConnection(Socket connection, String clientSentence){

serverConnection = connection;
sentence = clientSentence;

}

@Override
public void run() {
    Random r = new Random();
    String substring = sentence.substring(0, r.nextInt(sentence.length()));

try {
        OutputStream os = serverConnection.getOutputStream();
        OutputStream out = new BufferedOutputStream(os);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
        bw.write(substring);
        bw.close();
        out.close();
        os.close();


    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

I am using a Macintosh with Yosemite. Is this happening because I am trying to run the programs on the same computer, or would the problem occur if the programs were run from different computers? Any help is appreciated.

Irregular Square
  • 79
  • 1
  • 1
  • 7

2 Answers2

0

In the server you do a readLine(..), which means that it will wait for a end-of-line character.

But in your sender code, you just send a string with no line ending.

So either you make sure you also send a end of line char or your server wait's for something else as "delimiter"

André Schild
  • 4,592
  • 5
  • 28
  • 42
  • As similarly answered in [bufferedwriter-and-socket-in-java-write-has-no-effect](https://stackoverflow.com/questions/8275181/bufferedwriter-and-socket-in-java-write-has-no-effect) The OP might also want to check [Simple Java Client/Server Program](https://stackoverflow.com/questions/2165006/simple-java-client-server-program) – jwd630 Jul 27 '15 at 21:32
  • I did not know at first what such a delimiter could be, but after research I found that a "\n" at the end of the String would work. Thank you for answering my question (please tell me if simply adding a new line is bad practice and if I should be doing something else). – Irregular Square Jul 27 '15 at 23:46
  • You need some message delimiter, the newline is a good choice for this – André Schild Jul 28 '15 at 05:44
0

You're reading a line but you aren't writing a line. Add a line terminator to the sent message. Otherwise readLine() won't return until the peer closes the connection.

NB The I/O in the try block after the accept should be in the Runnable, not where it is. Don't do I/O in the accept loop.

user207421
  • 305,947
  • 44
  • 307
  • 483