I ve coded a simple Server that Listen for client and when the client is connected it opens a Datainputstream that read all the data sent from client( my client wirte UTF data).
This is the ServerCode:
@Override
public void run() {
// TODO Auto-generated method stub
try {
ServerSocket ss = new ServerSocket(7000);
while(true){
System.out.println("Il Server sta cercando Connessioni");
Socket s = ss.accept();
System.out.println("Il Server ha accettato un Client");
Thread t2 = new Thread(new Runnable(){
public void run(){
try {
while(true){
DataInputStream dis = new DataInputStream(s.getInputStream());
isAlreadyOpened = true;
System.out.println(dis.readUTF());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
isAlreadyOpened = false;
}
}
});
if(!isAlreadyOpened){
t2.start();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It is very basic and My client is an Andorid App that send data when button is clicked:
@Override
public void onClick(View v) {
try {
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.writeUTF("Testiamo sto socket");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Everything is perfect when the client is connected to the server. But when I click just one time the Client's button, the data sent is displayed in my server logs but immediatly after the exception is thrown.
Il Server sta cercando Connessioni
Il Server ha accettato un Client
Il Server sta cercando Connessioni
Testiamo sto socket
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
reading from Oracle documentation this exception is thrown <>. But how can I avoid this?
You are sending one string and then closing the connection. You are trying to read infinitely many strings. They aren't being sent. What you're getting instead is the expected EOFException.
There is no problem here to solve. If you need to send more strings over the same connection, don't close it after sending one.