I wrote two small java programs: a TCP client which sends many lines of data from a txt file, and a TCP Server which accepts connection and receives line by line.
It works, but Server receives all the lines together, when transmission is over and client closes the socket. I don’t understand why, because I’m using flush after each line sent into the Client, and I always thought that was to avoid this kind of situation.
If my test.txt file contents the numbers 1 2 3 … 10, each one in a new line, Server’s output is: “12345678910” and then in a new line it writes in console “null”.
Server code:
import java.io.*;
import java.net.*;
class ServidorTCP {
private String HOST;
static final int PUERTO = 20001;
public ServidorTCP( ) {
try{
ServerSocket skServidor = new ServerSocket(PUERTO);
Socket skCliente = skServidor.accept();
DataInputStream inFromClient = new DataInputStream(new BufferedInputStream(skCliente.getInputStream()));
while(true){
String lineaLeida = inFromClient.readUTF();
if(lineaLeida.equals("END")) break;
System.out.println(lineaLeida);
}
inFromClient.close();
skCliente.close();
skServidor.close();
System.out.println( "Transmission ended" );
} catch( Exception e ) {
System.out.println( e.getMessage() );
}
}
public static void main( String[] arg ) {
new ServidorTCP();
}
}
Cliente code:
import java.io.*;
import java.net.*;
class ClienteTCP {
static final String HOST = "192.168.1.201";
static final int PUERTO = 20001;
public ClienteTCP( ) {
try{
Socket skCliente = new Socket(HOST, PUERTO);
if(skCliente.isConnected()) System.out.println("Connected!");
DataOutputStream outToServer = new DataOutputStream(skCliente.getOutputStream());
File testFile = new File("test.txt");
BufferedReader input = new BufferedReader(new FileReader(testFile));
String line;
while((line=input.readLine())!=null) {
if(!line.endsWith("\n")) line = line + "\n";
System.out.println("Sending: " + line);
outToServer.writeBytes(line);
outToServer.flush();
Thread.currentThread().sleep(1000);
}
outToServer.writeBytes("END");
input.close();
outToServer.close();
skCliente.close();
} catch( Exception e ) {
System.out.println( e.getMessage() );
}
}
public static void main( String[] arg ) {
new ClienteTCP();
}
}
Where is the problem?
EDIT: I have edited the code as suggested. Now doesn’t receive anyhing
The fact of the matter is that your code doesn’t work at all, let alone before or after the socket is closed. You are writing with
writeUTF()and reading withreadLine().This does not work. You need to:write with
DataOutputStream.writeUTF()and read withDataInputStream.readUTF()write with
println()(supplied by several I/O classes), orwrite()orprint()(supplied by several I/O classes), followed byBufferedWriter.newline(), orwrite with
ObjectOutputStream.writeObject()and read withObjectInputStream.readObject().Etc. Writing with one API and reading with a non-symmetrical API doesn’t work.