an app in PC using JAVA io.socket which will sends json to a server device ESP8266on TCP on LAN network
when you are connected and when disconnect sequence is executed from java it self everything is ok .
java is client and device is server , when device cuts the connection (here lets use Hercules on localhost) the java program will not being noticed and when i try to write with outputstreamwriter it dose not trig an exception , exception will be executed after at least two writes to socket after the server is being disconnected and the last two writes which was not being received by server will return success! in java. i have read other programmers use a byte send to see if connection is still alive . the same problem is there too . if i send two write each 20 seconds time in between its going to be 60 seconds before java realize server is disconnected and if i send every 1 second is going to be a lot of ATcommand interrupts for nothing .
here is my code:
public boolean Write(String data){
System.out.println("StartSending");
if(TESocket.Connected)
{
Thread write = new Thread(new Runnable() {
#Override
public void run() {
try
{
outputStreamWriter.write(data);
outputStreamWriter.flush();
}
catch (IOException e)
{
TESocket.Connected=false;
System.out.println("Faild");
System.out.println(e.getCause());
}
}
});
write.start();
return true;
}
else
{
System.out.println("Not Connected");
return false;
}
}
The TESocket is class which handles Socket using Runnable and Connected is a static boolean since there is just one socket at a time here is the connect method
public boolean Connect(){
Thread connect = new Thread(new Runnable() {
#Override
public void run() {
try {
socket= new Socket("127.0.0.1",Integer.parseInt(port));
if(socket.isConnected())
{
inputStreamReader = new InputStreamReader(socket.getInputStream());
outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
TESocket.Connected=true;
System.out.println("Connected");
}
} catch (IOException e) {
System.out.println("Faild to Connect");
e.printStackTrace();
}
}
});
connect.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(TESocket.Connected)
return true;
else
return false;
}
how can i be noticed if server is out of reach with immediately after sending the write? or is there eny event for noticing that ? maybe some king of asynchronous socket? like it was in QT (Signal Slot for Disconnect)
well By reading method and setting a timeout solved this problem , thanks to reading some post
in read if i am still connected and not receiving any data time out will be thrown which bring me back to the first lie of the while loop
if i receive data i will be bigger than zero which reader will read data and flag the rec=true so the disconnect sequence dose not take in place
if i don't receive any data and timeout dose not occurs the rec=false and exception will not be thrown so the program will o to disconnect routine
setting the timeout to 1 millisecond makes it real-time (proportional to my work) in deadline detection
public boolean Read()
{
if (TESocket.Connected)
{
try {
socket.setSoTimeout(1000);
} catch (SocketException e) {
System.out.println("Problem Timeout");
e.printStackTrace();
}
Thread read = new Thread(new Runnable() {
#Override
public void run() {
int i;
boolean rec=false;
while (true)
{
char[] reader = new char[250];
try {
//while(!inputStreamReader.ready());
i=inputStreamReader.read(reader);
if(i>0) {
System.out.println(reader);
rec=true;
}
// Thread.sleep(2500);
if(!rec)
{
System.out.println("Disconnected");
TESocket.Connected=false;
inputStreamReader.close();
outputStreamWriter.close();
socket.close();
break;
}
rec=false;
}
catch (IOException e)
{
System.out.println("Connected");
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
read.start();
}
return true;
}
I have a problem with socket communication.
Sometimes reading from inputstream on client side stops working while the server is still sending new messages. I debugged the server so I know that is still working and sending messages to the outputstream. But on the client side read from inputstream is blocked. I can't debug this situation on client side. I only see difference in received messages on client side just before everything stops.
Example of good received message when everything works fine. Single send message in one line (I use DataInputStream.readUTF() method on client side and DataOutputStream.writeUTF(String msg) on server side. )
ADD;MB57,18-9,5,dd,10,10;
UP;MB15;20;14;20;13;1.0;
ADD;MB37,18-9,5,xx,10,10;
UP;MB13;20;14;20;13;1.0;
ADD;MB47,18-9,5,ww,10,10;
UP;MB13;20;14;20;13;1.0;
And this is happens just before my socket stop reading from input. One big mess. And everything that has been sent from the beginning in one line. It looks like the buffer overload O.o What happens?
11-07 11:36:41.978: I/System.out(17980): 11;8;10;8;0.1;��UPPOS;MB8;16;8;16;7;1.0;��PATH;MB8��UPPOS;MB20;14;9;14;10;1.0;�� ADDMOB;MB20,14-10,6,mummy,50,50;�� PATH;MB20��UPPOS;MB50;12;8;12;7;1.0;�� PATH;MB50��UPPOS;MB13;15;11;14;11;1.0;�� PATH;MB19��PATH;MB8��UPPOS;MB20;14;10;13;10;1.0;�� PATH;MB20��UPPOS;MB50;12;7;12;6;1.0;�� PATH;MB50��UPPOS;MB13;14;11;14;10;1.0;��UPPOS;MB19;13;9;14;9;1.0;�� PATH;MB19��PATH;MB8��UPPOS;MB20;13;10;13;9;1.0;��ADDMOB;MB20,13-9,6,mummy,50,50;�� PATH;MB20��UPPOS;MB50;12;6;12;7;1.0;�� PATH;MB50��UPPOS;MB13;14;10;15;9;1.0;��!ADDMOB;MB13,15-9,5,chicken,10,10;�� PATH;MB13��UPPOS;MB19;14;9;14;10;1.0;��!ADDMOB;MB19,14-10,1,goblin,37,50;�� PATH;MB19��UPPOS;NP12;10;8;9;8;0.1;��UPPOS;MB8;16;7;17;7;1.0;��PATH;MB8��UPPOS;MB20;13;9;12;9;1.0;�� PATH;MB20��UPPOS;MB50;12;7;11;7;1.0;�� PATH;MB50��UPPOS;MB13;15;9;14;9;1.0;�� PATH;MB13��UPPOS;MB19;14;10;13;9;1.0;�� ADDMOB;MB19,13-9,1,goblin,37,50;�� PATH;MB19��UPPOS;MB8;17;7;16;7;1.0;��PATH;MB8��UPPOS;MB20;12;9;12;8;1.0;��UPPOS;MB50;11;7;12;7;1.0;�� PATH;MB50��UPPOS;MB13;14;9;14;10;1.0;��"ADDMOB;MB13,14-10,5,chicken,10,10;�� PATH;MB13�� PATH;MB19��UPPOS;MB8;16;7;16;8;1.0;��PATH;MB8�� PATH;MB20�� PATH;MB50��UPPOS;MB13;14;10;15;10;1.0;�� PATH;MB13��UPPOS;MB19;13;9;14;9;1.0;�� PATH;MB19��UPPOS;NP12;9;8;9;9;0.1;��UPPOS;MB8;16;8;16;7;1.0;��PATH;MB8��UPPOS;MB20;12;8;12;9;1.0;�� PATH;MB20��UPPOS;MB50;12;7;12;6;1.0;�� PATH;MB50��UPPOS;MB13;15;10;14;10;1.0;��UPPOS;MB19;14;9;13;9;1.0;�� PATH;MB19��PATH;MB8��UPPOS;MB20;12;9;12;8;1.0;�� PATH;MB50��UPPOS;MB13;14;10;14;9;1.0;��!ADDMOB;MB13,14-9,5,chicken,10,10;�� PATH;MB13�� PATH;MB19��UPPOS;MB8;16;7;16;6;1.0;��PATH;MB8��UPPOS;MB20;12;8;12;7;1.0;�� PATH;MB20�� PATH;MB50��UPPOS;MB13;14;9;14;10;1.0;��"ADDMOB;MB13,14-10,5,chicken,10,10;�� PATH;MB13��UPPOS;MB19;13;9;13;10;1.0;��!ADDMOB;MB19,13-10,1,goblin,37,50;�� PATH;MB19��UPPOS;NP12;9;9;9;8;0.1;��PATH;MB8�� PATH;MB20��UPPOS;MB50;12;6;11;6;1.0;�� PATH;MB50��UPPOS;MB13;14;10;14;9;1.0;��!ADDMOB;MB13,14-9,5,chicken,10,10;�� PATH;MB13��UPPOS;MB19;13;10;13;9;1.0;�� ADDMOB;MB19,13-9,1,goblin,37,50;�� PATH;MB19��UPPOS;MB8;16;6;16;7;1.0;��PATH;MB8�� PATH;MB20��UPPOS;MB50;11;6;12;6;1.0;�� PATH;MB50��UPPOS;MB13;14;9;15;9;1.0;�� PATH;MB13�� PATH;MB19��PATH;MB8��UPPOS;MB20;12;7;12;8;1.0;�� PATH;MB20�� PATH;MB50��UPPOS;MB13;15;9;14;9;1.0;�� PATH;MB13��UPPOS;MB19;13;9;13;10;1.0;��!ADDMOB;MB19,13-10,1,goblin,37,50;�� PATH;MB19��UPPOS;NP12;9;8;10;8;0.1;��UPPOS;MB8;16;7;16;8;1.0;��PATH;MB8��UPPOS;MB20;12;8;12;7;1.0;�� PATH;MB20�� PATH;MB50��UPPOS;MB13;14;9;15;9;1.0;�� PATH;MB13��UPPOS;MB19;13;10;13;11;1.0;�� PATH;MB19��UPPOS;MB8;16;8;16;9;1.0;��PATH;MB8��UPPOS;MB20;12;7;11;7;1.0;�� PATH;MB20��UPPOS;MB13;15;9;14;9;1.0;�� PATH;MB50�� PATH;MB13��UPPOS;MB19;13;11;13;10;1.0;��UPPOS;MB20;11;7;12;7;1.0;�� PATH;MB20��UPPOS;MB8;16;9;16;8;1.0;�� PATH;MB50��UPPOS;MB13;14;9;15;9;1.0;�� PATH;MB13��UPPOS;MB19;13;10;14;10;1.0;��UPPOS;NP12;10;8;11;8;0.1;�� PATH;MB20��UPPOS;MB8;16;8;16;7;1.0;��PATH;MB8�� PATH;MB50��UPPOS;MB13;15;9;14;9;1.0;�� PATH;MB13��UPPOS;MB19;14;10;15;9;1.0;�� ADDMOB;MB19,15-9,1,goblin,37,50;�� PATH;MB19��UPPOS;MB20;12;7;11;7;1.0;�� PATH;MB20��UPPOS;MB8;16;7;16;6;1.0;��PATH;MB8��UPPOS;MB50;12;6;12;7;1.0;�� PATH;MB50��UPPOS;MB13;14;9;13;9;1.0;�� PATH;MB13��UPPOS;MB19;15;9;14;9;1.0;�� PATH;MB19�� PATH;MB20��UPPOS;MB8;16;6;16;7;1.0;��PATH;MB8��UPPOS;MB50;12;7;12;8;1.0;�� PATH;MB50�� PATH;MB13��UPPOS;MB19;14;9;14;10;1.0;��!ADDMOB;MB19,14-10,1,goblin,37,50;�� PATH;MB19��UPPOS;MB20;11;7;12;7;1.0;�� PATH;MB20��UPPOS;MB8;16;7;16;8;1.0;��PATH;MB8��UPPOS;MB50;12;8;12;9;1.0;�� PATH;MB50��UPPOS;MB13;13;9;14;9;1.0;�� PATH;MB13��UPPOS;MB19;14;10;15;10;1.0;�� PATH;MB19��UPPOS;MB20;12;7;11;7;1.0;�� PATH;MB20��UPPOS;MB50;12;9;12;8;1.0;�� PATH;MB50��UPPOS;MB8;16;8;16;7;1.0;��PATH;MB8��UPPOS;MB13;14;9;13;9;1.0;�� PATH;MB13��UPPOS;MB19;15;10;15;9;1.0;�� ADDMOB;MB19,15-9,1,goblin,37,50;��UPPOS;NP12;11;8;10;8;0.1;��UPPOS;MB20;11;7;12;7;1.0;��UPPOS;MB8;16;7;16;6;1.0;��PATH;MB8�� PATH;MB13��UPPOS;MB50;12;8;11;8;1.0
Client side
private DataOutputStream out;
private Socket client;
private DataInputStream in;
private Thread inputListener;
public void createConnection(){
try {
client = new Socket(serverName, port);
setOut(new DataOutputStream(client.getOutputStream()));
in = new DataInputStream(client.getInputStream());
inputListener=new Thread(){
public void run(){
try {
synchronized(in){
while(client!=null){
try{
String read = new String(in.readUTF());
/** do somethink with input msg */
} catch (java.io.UTFDataFormatException e1) {
e1.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
reconnect();
}
}
};
inputListener.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void reconnect() {
try {
client.close();
client=null;
inputListener.interrupt();
setOut(null);
in.close();
in=null;
} catch (IOException e) {
e.printStackTrace();
} finally{
System.out.println("RECONECT METHOD IN SOCKET");
}
}
Server side
private DataOutputStream out;
private Socket client;
public Client(Socket client) {
try {
setOut(new DataOutputStream(client.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String string) {
try {
getOut().writeUTF(string);
} catch (IOException e) {
e.printStackTrace();
disconected();
}
}
You must be writing something else to the stream. Catching and ignoring UTFDataFormatException is no solution. Once you get it, you will never get back into sync with the sender.
NB Converting the result of readUTF() to a String is futile. It already is a String.
I got to stage where client and server communicate, sending messages from and to each other.
The problem I am having is how to close the connection without causing an error?
If I terminate one of the apps (either server or client) that causes the connection to be lost, and then it causes the loop that is waiting for input to loop indefinitely and showing null's.
I tried closing sockets, buffers and even the thread, didn't work.
This is the client side
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
This is the server side
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(
socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Both use these classes:
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(
this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
//***HERE EXTRA BIT FOR THE SERVER
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(msg);
}
}
the only difference is the server has this bit where it says above ***HERE EXTRA BIT FOR THE SERVER
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Message recieved");
so basically, client connects, server accepts, then client sends message, servers receives message and shows it, and then sends "Message received" to the client, and the client shows it.
All this works fine, but once the connection is lost, they hang on showing null repeatedly, and I have to force the app to close.
You aren't checking for end of stream. If readLine() returns null, the peer has closed the connection, and you must do likewise and stop reading.
It's hard to believe you really need a new thread for every line to update the UI.
i am creating a multiple-client/server app whenever any client disconnects from
my server it just hangs.
how can i set any condition that will tell me print some message whenever
any client disconnects from the server
here is my server code
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
System.out.println("server starting.......");
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println("Ready to accept.......");
socket = serverSocket.accept();
System.out.println(" client Connected with ip address =" +socket.getRemoteSocketAddress().toString());
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
System.out.println("catch block");
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
any help will be appreciated
It's not clear whether you mean disconnect because the conversation was over (ie: everything completed successfully) or the disconnect is because of some network problems (or the client canceled the request).
If it's the first case, then it's easy: the protocol you are using (your own, or http, or whatever) is in charge of defining how to determine that a conversation was over. If that situation arises, then you just close the socket.
If it's the second case, then you'd have to have an algorithm in place to determine whether or not the connection must be closed. For instance, by implementing a timeout, or a slow-read threshold. Take a look at the Socket's javadoc for instructions on how to set a timeout.
It's also worth noting that it's fine to create your own servers when you want to practice or learn something, but you'd be better off using an existing solution, like vert.x or a slimmed down version of Wildfly, for instance. The overhead of such servers is very low, nowadays, while still providing very robust networking capabilities.
Below I have put a fragment of code to help understand my problem. I have a server code, works fine for the first time the client loads and sends a packet. After the first packet is received, the server is stuck on "accept".
I have wireshark configured for this port, and the server is getting those packets. I just wonder why accept wont return more than once. Its driving me nuts.
Server Code
public class DAPool implements Runnable {
private ServerSocket serverSocket;
private ArrayList<DA> pool;
private LinkedList<Socket> clientConnQ;
public DAPool(int newPoolSize, int serverPort) {
try {
serverSocket = new ServerSocket(serverPort, 500, InetAddress.getByName("127.0.0.1"));
} catch (IOException e) {
e.printStackTrace();
return;
}
poolSize = newPoolSize;
clientConnQ = new LinkedList<Socket>();
pool = new ArrayList<DA>(poolSize);
DA deviceThread;
for (int threads = 0; threads < poolSize; threads++) {
deviceThread = new DA();
connPool.add(deviceThread);
deviceThread.start();
}
}
public void run() {
while (true) {
Socket incomingSocket;
try {
incomingSocket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
return;
}
insertNewConnToQ(incomingSocket);
}
}
private class DA extends Thread {
private Socket clientSocket;
private ObjectInputStream inputObjectStream;
public DA() {
}
public void run() {
while (true) {
while (clientConnQ.isEmpty()) {
synchronized (clientConnQ) {
try {
clientConnQ.wait();
} catch (InterruptedException ignored) {
ignored.printStackTrace();
}
}
}
synchronized (clientConnQ) {
clientSocket = (Socket) clientConnQ.removeFirst();
try {
inputObjectStream = new ObjectInputStream(clientSocket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return;
}
// Do something useful here
}
}
}
}
}
Client Code
public class SendQueue extends Thread {
LinkedList<Message> requestQ;
Message sendRequest, requestMessage;
Socket clientSocket;
OutputStream outputStream;
ObjectOutputStream objectOutputStream;
public SendQueue(Socket newClientSocket) {
requestQ = new LinkedList<Message>();
clientSocket = newClientSocket;
}
public void run() {
while (true) {
synchronized (requestQ) {
while (requestQ.isEmpty()) {
try {
requestQ.wait();
} catch (InterruptedException ignored) {
ignored.printStackTrace();
}
}
sendRequest = requestQ.removeFirst();
}
try {
outputStream = clientSocket.getOutputStream();
objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(sendRequest);
objectOutputStream.flush();
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
public int sendRequest(Message message) {
synchronized (requestQ) {
requestQ.addLast(message);
requestQ.notify();
}
return 0;
}
}
I don't see a timeout being set on the serverSocket.
ServerSocket.accept() is a blocking operation so it will block until either an error occurs, a timeout occurs, or a connection is accepted.
Try
SererSocket.setSOTimeout(10000)
You also don't seem to be closing your streams when your finished.
Are you sure that it is sticking on the accept call? Did you get a stacktrace that shows it waiting on accept?
Assuming it is getting stuck elsewhere I'm wondering if it isn't because clientConnQ is being held in one of your DA instances. The synchronized block covers the // Do something useful here section.
I wonder if it might work if you changed the code to be
synchronized (clientConnQ) {
clientSocket = (Socket) clientConnQ.removeFirst();
}
try {
...
Once you have your clientSocket from clientConnQ then no other instance can process that socket.
Ok, if I got a $ for everytime I asked a silly question :)
Here goes. A client socket connects and thats when a server receives a accept call. For some silly reason I was waiting on accept for receiving further data from the client. Infact, I should just wait for something on the "stream" and then process the stream. I should not wait on the accept for that connection.
Accept is to be called to "connect" to the socket, not to receive data continuously.
Thanks for your all your help. You forced me to think about thread synchronization, the design, sockets in general and finally arrive that the solution.
Fantastic responses people. Thanks.
Siddharth