java socket disconnected from server side - java

I am facing a problem regarding sockets on the server side. My code is client side. Whenever I am sending a second message (whether it's a heartbeat or any other message) it will fail on the server, and the server side logs an 'error in message format' but the same message will succeed the first time.
Please help me out with this.
my client code :
public class Main {
String Host = "";
int port = 1111;
Socket ss;
BufferedReader in;
BufferedWriter out;
String recv;
public void connection() {
try {
ss = new Socket(Host, port);
ss.setSoTimeout(30000);
in = new BufferedReader(new InputStreamReader(ss.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(ss.getOutputStream()));
} catch (UnknownHostException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sender(String regTag) {
if (ss == null || !ss.isConnected()) {
connection();
}
try {
if (out != null && regTag != null) {
out.write(regTag + "\n");
System.out.println("message::" + regTag);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String Reciver() {
try {
recv = in.readLine();
if (ss != null && recv != null) {
return recv;
} else {
disconnect();
String Str = "nothing...Sorry";
return Str;
}
} catch (Exception e) {
e.printStackTrace();
return "Exception";
}
}
public void disconnect() {
try {
System.out.println("socket discoonected.");
ss.close();
in.close();
out.close();
connection();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Main me = new Main();
me.connection();
String hbhb = "`SC`0004HBHBB7BDB7BD";
String login = "`SC`00581.000000CRBTSRVM 00000001DLGLGN 00000002 TXBEG LOGIN:USER=cvbs,PSWD=password DEB2CCA8";
String cut = "`SC`00631.000000CRBT00PPSPHS00000002DLGCON 00000003 TXBEG CUT PPS FEE:MDN=9610023,CUTFEE=1000,REASON=1 BDB7DA88";
me.sender(hbhb.trim());
String str = me.Reciver();
System.out.println("Response :::" + str);
me.sender(login.trim());
String str1 = me.Reciver();
System.out.println("Response hb:::" + str1);
}
It receives null ... all the time on every second message
logs from serverside
[121_SERVER] 2012-05-03 14:26:37:213 [ERROR] [ServerAccptor.java:254] ->
errorCode = [UIP-80015] errorDesc = [Uip server has a exception when receiving data from the client,will remove the client,Server [adapter id=121],.]
at com.ztesoft.zsmart.bss.uip.adapter.socket.server.ServerAccptor.listenMsg(ServerAccptor.java:252)
at com.ztesoft.zsmart.bss.uip.adapter.socket.server.ServerAccptor.run(ServerAccptor.java:117)
Caused by: errorCode = [UIP-9102] errorDesc = [] Describing= [read client message error,will remove client.]
at com.ztesoft.zsmart.bss.uip.adapters.socket.server.mml.MMLServerAdapter.readByteField(MMLServerAdapter.java:784)
at com.ztesoft.zsmart.bss.uip.adapters.socket.server.mml.MMLServerAdapter.reciveWholeMsg(MMLServerAdapter.java:671)

Your code embodies numerous bad practices and fallacies.
You are logging exceptions and otherwise ignoring them, and doing strange things like letting the program continue, returning "Exception", etc. This is poor programming. Exceptions are there to help you, not to have bandaids applied them to hide the blood. The code will not self-heal under the bandaid. For example you should just declare connection() to throw IOException and let the callers deal with it.
As a consequence of (1) you have numerous ss != null tests. You shouldn't even be in a state where you need to do I/O and ss could be null. Again correct exception handling and propagation would avoid this.
As a further result of (1), you have numerous !ss.isConnected() tests, apparently in the mistaken belief that this API will tell you if the connection has been dropped. It won't. It will only tell you whether you have connected the Socket yet. In your code, as you are calling ss = new Socket(...), you have connected it, or else you haven't executed that code yet. Calling isConnected() adds no value.
You are closing the socket input stream before the output stream. This is incorrect. You should close only the output stream, and the socket itself in a finally block. That way the output stream gets flushed. Closing the input stream closes the socket and the output stream without flushing it. Don't do that.

Actually the correct answer is that there is no \n in the MML response. So this never works:
recv = in.readLine();
You have to read the message length given in the message header part of the response and read up to that length.
UPDATE:
there are syntax errors in your MML commands. It seems that you are using version 1.00 of the protocol, so this is a sample that works (look for differences):
`SC`00741.00CRBT PPS 00000001DLGCON 00000004TXBEG PPS CUT FEE:mdn=93784050910,fee=300,id=20140812165011003 F3E0ADDF
You must fill the extra spaces with 0 just in numbers, elsewhere you have to fill them with blank spaces.

Related

Detecting when a client has disconnected from my server [duplicate]

This question already has answers here:
Java socket API: How to tell if a connection has been closed?
(9 answers)
Closed 5 years ago.
I'm trying to find a way to see when a client that is connected to my server has disconnected. The general structure of my code is like this, I have omitted irrelevant sections of my code:
public class Server {
public static void main(String[] args) {
...
try {
ServerSocket socket = new ServerSocket(port);
while (true) {
// wait for connection
Socket connection = socket.accept();
// create client socket and start
Clients c = new Server().new Clients(connection);
c.start();
System.out.printf("A client with IP %s has connected.\n",c.ip.substring(1) );
}
} catch (IOException exception) {
System.out.println("Error: " + exception);
}
}
class Clients extends Thread {
...
public Clients(Socket socket) {
clientSocket = socket;
ip=clientSocket.getRemoteSocketAddress().toString();
try {
client_in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
client_out = new PrintWriter(clientSocket.getOutputStream(), true);
} catch (IOException e) {
//error
}
}
public void run() {
...
try {
while (true) {
while ((message = client_in.readLine()) != null) {
...
}
}
} catch (IOException exception) {
System.out.printf("Client with IP %s has disconnected.\n" , ip.substring(1));
}
}
}
}
Basically what I'm trying at the moment is detecting the disconnection through the catch statement in run(), but the issue with this is it doesn't display the message until I terminate my server.
I have also tried to put my print statement after the while(true) loop but my IDE tells me that code is unreachable.
Is there a way to get my "Client with IP %s has disconnected." to display as soon as the client connection is disconnected? What and where should I be checking?
what I'm trying to do is detecting the disconnection through the catch statement.
Bzzt. readLine() doesn't throw an exception at end of stream. It returns null. Any exception you catch here is an error, and should be reported as such.
while (true) {
while ((message = client_in.readLine()) != null) {
...
}
The problem is here. You are detecting when the peer disconnects: readLine() returns null and terminates the inner loop. However you have pointlessly enclosed the correct inner read loop in an outer while (true) loop, which by definition can never exit.
Remove the outer loop.

Socket closed before able to read from ObjectInputStream(BufferedInputStream(Socket.getInputStream))

I have written a small Client/Server Program which already worked once but after adding Threads and some real input Data to it, i always get a closed Socket before being able to read the Object (the String). The Program always Prints "Client has already closed Connection!" from Function handleConnection in the ProcessDataThread.
ClientCode:
synchronized private static void sendToServer(){
Socket clientSocket = null;
BufferedOutputStream socketOut = null;
ObjectOutputStream out = null;
try{
String xmlToSend = "<startTag>\n<someOtherTag id=\"5555\">\n12345\n</someOtherTag>\n</startTag>\n";
Log.d(TAG, "Trying to send the following to the Server:" + xmlToSend);
//TODO load these from file
clientSocket = new Socket( "10.0.2.2", 7777);
socketOut = new BufferedOutputStream(clientSocket.getOutputStream());
out = new ObjectOutputStream(socketOut);
out.writeObject(xmlToSend);
out.flush();
}catch(Exception ex){
Log.e(TAG, "Could not write File to Server.", ex);
}
finally{
try{
if(clientSocket != null){
clientSocket.close();
}
if(out != null){
out.close();
}
}catch(IOException ex){
Log.e(TAG, "Could not close Socket.");
}
}
}
ServerCode:
ReceiverThread:
public void run()
{
try {
ServerSocket server = new ServerSocket(port);
//Only block for 10 Seconds and try again
server.setSoTimeout(10000);
while(!server.isClosed() && !stopped){
//Run
Socket client = null;
try
{
client = server.accept();
System.out.println("Accepted ClientConnection from " + client.getRemoteSocketAddress());
new ProcessDataThread(client).start();
}
catch( SocketTimeoutException tx){
//nothing
}
catch ( IOException e ) {
e.printStackTrace();
}
finally {
if ( client != null )
try { client.close(); } catch ( IOException e ) { e.printStackTrace(); }
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
ProcessDataThread:
public class ProcessDataThread extends Thread {
Socket client;
public ProcessDataThread(Socket sock) {
// xmlToProcess = xmlString;
this.client = sock;
}
private String handleConnection() {
BufferedInputStream socketIn = null;
ObjectInputStream in = null;
String xmlToProcess = null;
try {
if(!client.isClosed()){
System.out.println("Trying to read from Stream;");
socketIn = new BufferedInputStream(client.getInputStream());
in = new ObjectInputStream(socketIn);
Object xmlString = in.readObject();
System.out.println("Read some Object from Stream:" + xmlString.toString());
if (xmlString instanceof String) {
xmlToProcess = (String) xmlString;
System.out.println("Received the following XML:\n" + xmlToProcess);
}
}else{
System.out.println("Client has already closed Connection!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (EOFException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socketIn != null) {
socketIn.close();
}
if(client != null){
client.close();
}
} catch (IOException ioex) {
ioex.printStackTrace();
}
}
return xmlToProcess;
}
#Override
public void run() {
String xmlToProcess = handleConnection();
if (xmlToProcess == null || xmlToProcess.isEmpty()) {
// Es konnte kein String vom Client gelesen werden.
return;
}
System.out.println(xmlToProcess);
}
}
I made some changes with jboi's Suggestions. This is what i got now. The error stays the same. I don't even get to reading the Stream in the Server because client.getClosed()
is always true!
In the Client Code:
clientSocket = new Socket( "10.0.2.2", 7777);
clientSocket.setTcpNoDelay(true);
socketOut = new BufferedOutputStream(clientSocket.getOutputStream());
out = new ObjectOutputStream(socketOut);
out.writeObject(xmlToSend);
out.flush();
socketOut.flush();
//Close Output on Socket to signalize the Server that we finished writing!
clientSocket.shutdownOutput();
in = clientSocket.getInputStream();
byte[] receivedData = new byte[8192];
while(in.read(receivedData) != -1) {
//Wait for the Server to Close the Connection
}
In the Server Code
socketIn = new BufferedInputStream(client.getInputStream());
in = new ObjectInputStream(socketIn);
Object xmlString = in.readObject();
System.out.println("Read some Object from Stream:" + xmlString.toString());
if (xmlString instanceof String) {
xmlToProcess = (String) xmlString;
System.out.println("Received the following XML:\n" + xmlToProcess);
}
out = client.getOutputStream();
out.write(1);
//Signalize the Client that we have read everything
client.shutdownOutput();
It is very probable that your client has closed the socket in the finally block before the server was able to read the data.
In your clients finally block you should use socket.shutdownOutput, then read on the client all incoming data till EOF and then close the socket.
On your server you read till EOF and then send an object as kind of acknowledge, e.g. Number of bytes in the message. You also end the send with socket.shutdownOutput() as you've done at the client. This puts again an EOF at the end of the data. This EOF is received by the client and it will finally close the socket.
The issue seems to be the client and server are unable to identify each others state:
Client sending data to server, where server has closed the connection
Server sending/reading data to client , where client has closed the connection
Either are unable to coordinate with each other, solutions could be to establish a proper state machine. Some examples in Google if you search for (client and server state machine) gives mathematically definite state machine examples for your application: hope this comment helps.
Hence it's not useful to look into this problem in solution perspective and probably start using protocols in place like : telnet etc .
Ok now i'm feeling stupid.
I closed the Socket inside the Server Code myself.
After accepting a connection the following is executed inside the finally Block:
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
The reason that there is this finally Block was because i didn't use Threads before so the ReceiverThread also did handle the Connection and therefore close the socket after using it.
I then moved the code to the new Thread and forgot to remove that finally block!
You can't use a buffered input stream and another kind of stream on the same socket. The buffered stream will steal data from the other one. Make up your mind. The ObjectInputStream will do everything you need. Just use that.
EDIT Re your edit, 'socket closed' means that you closed your socket and then continued to use it.

Communication via standard input / output in Java

I am trying to send messages between two JVMs: a server starts a second process. The second process is then to send a message to the server which prints the message to the console. The code is as follows:
public class Server
{
public static void main(String[] args)
{
Process client=null;
BufferedReader clientInput=null;
try
{
client=Runtime.getRuntime().exec("java Client");
clientInput=new BufferedReader(new InputStreamReader(client.getInputStream()));
}
catch(IOException e){}
System.out.println("Waiting for the client to connect...");
try
{
String msg=clientInput.readLine();
System.out.println(msg);
}
catch(IOException e){}
client.destroy();
}
}
and
public class Client
{
public static void main(String[] args)
{
BufferedWriter out = new BufferedWriter( new OutputStreamWriter(System.out));
try
{
out.write("Ready\n");
out.flush();
}
catch (Exception e){}
}
}
If I run this, I get as output from the server null. In the end, the communication should be both ways. Any help greatly appreciated.
EDIT: I don't get any errors (just removed the print statements from the catch blocks to save space).
I think you need to add a while loop:
while ((s = in.readLine()) != null && s.length() != 0)
System.out.println(s);
}
You receive null at the end of the stream. The client correctly starts, sends Ready, and the the ends, so the stream ends.
Totally correct behaviour. If the client would end itself (but instead do something else like reading server messages on stdin), the server would never receive a null.
Edit: NEVER EVER (!!!!!) do this:
catch(IOException e){}
At least write:
catch(IOException e){ e.printStackTrace() }
This will show you your error!
In my company, this is one of the elementary rules of code style!

Java/android socket.close() is not realized by server

I'm having an issue trying to get a java server to realize an (android/java) client has closed a TCP socket connection. I figured when the client calls close() on the socket, the server would catch an IOException, but this is not the case. t_recv is a thread that receives from BufferedReader in, and t_send sends using a PrintWriter out. Closing in causes a timeout and crash, and closing out doesn't really seem to do anything. The PrintWriter is created in the contructor of the t_send thread, and BufferedReader is create in the contructor of the t_recv thread. Trying to debug this, I created blank run() methods in both threads, and the same behaviour occurs.
An interesting note: the client is an Android application, and whenever the emulator freezes and windows has to force close it, the IOException is caught in the server and the "User x.x.x.x left" message is displayed.
Client closing connection:
try {
// t_recv.in.close(); - times out and crashes
// t_send.out.close(); - appears to do nothing
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
Server waiting for client to disconnect:
for (;;)
{
try {
while ( (msg = in.readLine()) != null)
{
response = msg;
System.out.println(response);
server.broadcast(response);
}
} catch (IOException e) {
System.out.println("User '" + socket.getInetAddress().toString() + "' left");
try {
socket.close();
out.close();
in.close();
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
}
break;
}
}
Thanks for your time.
Assuming that in is a BufferedReader, the error is in this line:
while ( (msg = in.readLine()) == null);
That will loop for ever if in is currently at the EOF. It should be:
while ( (msg = in.readLine()) != null);
See javadoc for BufferedReader.readLine(), paying specific attention to the conditions in which it returns null.

java socket server, client detect server has died

If I kill the Socket Server process, my Socket client process does not receive any errors, it continues to loop forever on the following code:
public void run() {
while(readData) {
String inputLine = null;
try {
while((inputLine = m_inputStream.readLine()) != null) {
//do stuff
}
} catch (IOException e) {
readData = false;
}
}
}
How can I detect that the socket server is gone and terminate the loop?
Terminate the outer loop when the call to readLine() returns null.
No exception is thrown when the server closes the connection normally. The stream should return null to signal the end of data.
This can be done with a loop like this:
public void run() {
try {
while (true) {
String line = input.readLine();
if (line == null)
break;
/* Process line. */
...
}
} catch (IOException ex) {
/* Handle the exception as desired. */
ex.printStackTrace();
}
}
Whilst the answer from erickson is correct, have you tried setting the socket read time-out properties? (e.g. sun.net.client.defaultReadTimeout). If it is possible that the server may take a long time responding, then this might be less useful as a solution to your problem but is a good idea nevertheless in many scenarios.

Categories