EOFException after readUTF randomly - java

I am developping an Android app and a java desktop app. The Android app send to the java desktop the sms received, and the desktop app provide an interface for answering to these sms.
The android app is the server, the desktop app connects to it through a socket.
Here is the code of the server (android app side)
public class Server extends AsyncTask<Void, Void, Void> {
public void stopServ(){
this.run=false;
}
public void newSMSReceived(String sms, String phone){
//SEND THE NEW SMS TO THE DESKTOP APP
try {
outputStream.writeUTF(new String(sms.getBytes(),"ISO-8859-1"));
outputStream.flush();
outputStream.writeUTF(new String(phone.getBytes(),"ISO-8859-1"));
outputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... params) {
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_SERVER_PORT);
Socket s = ss.accept();
System.out.println("connection received !");
inputStream = new ObjectInputStream(s.getInputStream());
outputStream = new ObjectOutputStream(s.getOutputStream());
outputStream.writeObject(contacts);
outputStream.flush();
while(true){
//READ THE MESSAGE SENDED FROM THE DESKTOP APP
message=inputStream.readUTF();
phone=inputStream.readUTF();
smsManager.sendTextMessage(phone.replaceFirst("0", "\\+33"), null, message, null, null);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
The desktop app side :
public class Main extends Application {
public Main(){
try {
PropertiesRetriever prop = new PropertiesRetriever();
socket = new Socket(prop.getIp(), 5657);
outputStream = new ObjectOutputStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
Thread listener = new Thread(new Runnable() {
public void run() {
while(true){
String message,phone;
Contact contact;
try {
//RECEIVED THE MESSAGE FROM THE ANDROID APP
message=inputStream.readUTF();<--- EOFException
phone=inputStream.readUTF();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
listener.start();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void sendMessage(Contact contact, Message message){
try {
//SEND THE MESSAGE TO THE ANDROID APP
outputStream.writeUTF(message.getTextUTF());
outputStream.flush();
outputStream.writeUTF(contact.getPhoneUTF());
outputStream.flush();
System.out.println(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**...**/
}
The details of the method "getxxUTF":
String rtr=null;
try {
rtr = new String(text.getBytes(),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rtr;
EOFException :
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:340)
at java.io.ObjectInputStream$BlockDataInputStream.readUnsignedShort(ObjectInputStream.java:2818)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(ObjectInputStream.java:2874)
at java.io.ObjectInputStream.readUTF(ObjectInputStream.java:1073)
Thing is, at a point, I get an EOFException on the readUTF mentioned above. Everything works fine until a certain point, and I have no clue why... Someone ?

You get this not 'randomly' but when the peer has closed the connection.

Related

Gui is hanging while sending command through telnet (Java programming)

Hello I'm trying to make a connection to a device with openocd as a server and telnet as client connection. When I try to send command through telnet via java programming my Java Gui hangs without giving any error. Someone please help me to understand the procedure for sending command and receiving response from the telnet.
Main code is as follows:
public class JTagMain
{
static TelnetClient telnet;
public static void halt() {
telnet = new TelnetClient();
try {
telnet.connect("localhost", 4444);
String cmd = "halt";
telnet.getOutputStream().write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
readWrite(telnet.getInputStream(), telnet.getOutputStream(),
System.in, System.out);
try {
telnet.disconnect();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.exit(0);
}
public static final void readWrite(final InputStream remoteInput,final OutputStream remoteOutput, final InputStream localInput,
final OutputStream localOutput)
{
System.out.println("-----readwrite---");
Thread reader, writer;
reader = new Thread()
{
public void run()
{
int ch;
try
{
while (!interrupted() && (ch = localInput.read()) != -1)
{
remoteOutput.write(ch);
remoteOutput.flush();
}
}
catch (IOException e)
{
//e.printStackTrace();
}
}
};
writer = new Thread()
{
public void run()
{
try
{
Util.copyStream(remoteInput, localOutput);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
};
writer.setPriority(Thread.currentThread().getPriority() + 1);
writer.start();
reader.setDaemon(true);
reader.start();
try
{
writer.join();
reader.interrupt();
}
catch (InterruptedException e)
{
//e.printStackTrace();
}
}
public static void telnetconnection()
{
telnet = new TelnetClient();
try {
telnet.connect("localhost", 4444);
System.out.println("telnetconnection");
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args)
{
JtagGui window = new JtagGui();
window.frame.setVisible(true);
try{
telnetconnection();
}
catch(Exception e){
System.out.println("connection failed");
}
}
}
If I try to call halt() command through Gui, it hangs without giving any response.
If I try with command prompt, it gives proper response.
Someone please help me to solve this issue.Thanks in advance.

how many users can handle on android client, pc java server with socket?

I made a simple app works with socket to transfer data between client and server over local network,
Server java codes:
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
String message = dataInputStream.readUTF();
// System.out.println("message: " + dataInputStream.readUTF());
try {
JSONObject jObj = new JSONObject(message);
String flag = jObj.getString("flag");
if (flag.equals("request")) {
String request = jObj.getString("request");
if (request.equals("getGroup"))
dataOutputStream.writeUTF(getGroup());
else if (request.equals("getFood")) {
String groupID = jObj.getString("groupID");
dataOutputStream.writeUTF(getFood(groupID));
}
}
} catch (JSONException | IOException e) {
e.printStackTrace();
}
// dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
and android client codes:
class Load extends AsyncTask<String, String, String> {
String response;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.106", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(utils.getGroup());
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
protected void onPostExecute(String file_url) {
showGroup(response);
}
}
How many clients this can handle?
Is there a better solution?
How many clients this can handle?
Basically your code is an iterative server. There’s one big loop, and in each pass through the loop a single connection is completely processed.
A: So in this sense it can handle only one client at a time.
If you want to suport more than one client at a time your server should service multiple clients simultaneously through the use of threads (one thread per each client connection).
The basic flow of logic in such a server is this:
while (true) {
accept a connection;
create a thread to deal with the client;
}
Please refer to the following tutorial for a full explanation and even some code example.
Is there a better solution?
In the Android side, as pointed out in my comment based in the answer here. Using AsyncTask for HTTP communications can have some drawbacks like:
You cannot cancel a request during execution.
The patterns of using AsyncTask also commonly leak a reference to an Activity...
A: A library like OkHttp can apply as a more robust alternative.

Program stop working when try to read input stream

I have a Java Server and one(or more) Android Clients. For now I want them to communicate simply with strings. When i write from android I can get the data in Java Server, but when I try to get the answer from server the Android application stop working. The codes is reported below:
Java Server:
public class Server {
private static int port=12346, maxConnections=0;
// Listen for incoming connections and handle them
public static void main(String[] args) {
int i=0;
try{
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)){
doComms connection;
server = listener.accept();
String end = server.getInetAddress().toString();
System.out.println("\n"+end+"\n");
doComms conn_c= new doComms(server);
Thread t = new Thread(conn_c);
t.start();
}
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private String line,input;
public doComms(Socket server) {
this.server=server;
}
#SuppressWarnings("deprecation")
public void run () {
input="";
try {
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(server.getOutputStream())),
true);
while((line = in.readLine()) != null && !line.equals(".")) {
input=input + line;
}
JOptionPane.showMessageDialog(null, input);
out.println("Enviado");
server.close();
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
And Android client's code (it's called every time a button is pressed inside onClick method):
public String enviaMensagem(){
String resposta="";
new Thread(new ClientThread()).start();
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(ip, port);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(input.getText().toString());
resposta = dataInputStream.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return resposta;
}
You are using an unsorted mixture of readUTF(), writeUTF(), readLine(), etc. They're not all interoperable. Settle on one of them. If you use writeUTF() you must use readUTF() at the other end. If you use readLine() you must write lines at the other end, with a line terminator such as \r\n or \n.

Socket ObjectOutpuStream ObjectInputStream

I'm writing simple client - server application. Everything is ok but when i change InputStream and OutputStream to ObjectOutputStream and ObjectInputStream my application doesn't send the messages. Can anyone help me and show me the problem ?
Here is the Serwer.java:
class InWorke implements Runnable{
BufferedReader odczyt=null;
String slowo;
ObjectInputStream ois=null;
Message message;
InWorke(ObjectInputStream ois) {
this.ois=ois;
}
public void run() {
while(true) {
try {
slowo = (String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(slowo);
Thread.yield();
} }
}
class OutWorke implements Runnable{
Socket socket=null;
BufferedReader odczytWe=null;
DataOutputStream zapis=null;
String slowo=null;
Message message; // it is the simple class to serialization
ObjectOutputStream oos;
OutWorke(Socket socket,ObjectOutputStream oos) {
this.socket=socket;
this.oos=oos;
}
public void run() {
while(true) {
odczytWe=new BufferedReader(new InputStreamReader(System.in));
try {
slowo=odczytWe.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos.writeObject(slowo);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Thread.yield();
}
}
}
public class Klient {
public static void main(String[] args) {
Socket socket=null;
ExecutorService exec=Executors.newCachedThreadPool();
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
try {
socket=new Socket("localhost", 8881);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//we=socket.getInputStream();
ois=new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//wy=socket.getOutputStream();
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
exec.execute(new OutWorke(socket, oos));
exec.execute(new InWorke(ois));
}
}
Klient.java:
class InWorker implements Runnable{
Socket socket=null;
//InputStream we=null;
//OutputStream wy=null;
String slowo=null;
BufferedReader odczyt=null;
ObjectOutputStream oos;
ObjectInputStream ois;
Message message=null;
InWorker(Socket socket,ObjectInputStream ois) {
this.socket=socket;
this.ois=ois;
}
public void run() {
while(true) {
try {
slowo=(String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(slowo);
Thread.yield();
}
}
}
class OutWorker implements Runnable{
DataOutputStream zapis=null;
BufferedReader odczyt=null;
//OutputStream wy=null;
String tekst=null;
ObjectOutputStream oos=null;
Message message;
OutWorker(ObjectOutputStream oos) {
this.oos=oos;
}
public void run() {
while(true) {
odczyt=new BufferedReader(new InputStreamReader(System.in));
try {
tekst=odczyt.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
oos.writeObject(tekst);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Thread.yield();
}
}
}
public class Serwer {
public static void main(String[] args) {
ServerSocket serversocket=null;
Socket socket=null;
//InputStream we=null;
//OutputStream wy=null;
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
ExecutorService exec=Executors.newCachedThreadPool();
try {
serversocket=new ServerSocket(8881);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serversocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois=new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
exec.execute(new InWorker(socket, ois));
exec.execute(new OutWorker(oos));
}
}
Check constructor of ObjectInputStream: constructor.
It says:
This constructor will block until the corresponding ObjectOutputStream
has written and flushed the header.
So you need to create and flush corresponding ObjectOutputStream. Now you are creating ObjectInputStreams before output stream for both server and client. They block programs because no output stream is created. You should create output streams first, call flush on them and only then create input streams.
The root issue is just as Nikita points out. The implementation solution is to have the server and client get the input and output streams in the opposite order. If one is getting the inputstream first have the other get the outputstream, etc. I switched the client to get the outputstream first and it all works. I then put it back and change the Server and it all works that way to... you can choose which to change.
For Reference:
http://docs.oracle.com/javase/6/docs/api/index.html?java/io/ObjectOutputStream.html

Socket write error when i connect multiple client to java server simultaneously

I am creating a desktop application in which multiple clients have to connect to the server using socket connection between them. I successfully connected them but the problem occurs when i connect multiple client simultaneously to the server, sever got an error "socket write error"
my code is below plz suggest me an answer..
public class SocketConnection implements Runnable {
// password of oracle database
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
Socket clientSocket = null;
DBConnection dbConnection;
public SocketConnection() {
// TODO Auto-generated constructor stub
dbConnection = new DBConnection();
if (con != null) {
serverSocket = dbConnection.createSocket();
if (serverSocket != null) {
System.out.println("Server Started. Looking for the connections.");
System.out.println("Listening Port:8888.......");
}
Thread t = new Thread(this);
t.start();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
clientSocket = serverSocket.accept();
System.out.println("Connection Accepted");
Connect m_connect = new Connect(clientSocket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Connect implements Runnable {
Socket clientSocket = null;
Thread t = null;
private ResultSet res1;
private ResultSet res2;
Statement stmt;
private File mkFolder;
public Connect(Socket clientSocke) {
// TODO Auto-generated constructor stub
this.clientSocket = clientSocke;
try {
stmt = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
t = new Thread(this);
t.start();
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(
clientSocket.getInputStream());
dataOutputStream = new DataOutputStream(
clientSocket.getOutputStream());
System.out.println("Connection established::"
+ clientSocket.getInetAddress());
String pass = dataInputStream.readUTF();
System.out.println(pass);
if (pass.equals("1")) {
//here is read n write operation
} else if (pass.equals("3")) {
//here is read n write operation
} else if (pass.equals("2")) {
//here is read n write operation
} else if (pass.equals("4")) {
//here is read n write operation
} else if (pass.equals("5")) {
//here is read n write operation
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Why you are doing this in that low-level way? Choose an well documented API and communicate through it!
Did you already read articles like this: Multithread client server chat on sockets. Load test. recv failed

Categories

Resources