I can`t understand something simple. I have a class that handles the socket input. I have a catch-clause:
public class EntryPoint implements Runnable {
private Socket socket = null;
private BufferedReader br = null; // receives data from the destination
...
public void run() {
String command = null; // buffer for holding one request from command line
StringReader commandReader = null; // stream for reading command
try {
while (!socket.isClosed() && (command = br.readLine()) != null) {
try {
command = command.trim();
commandReader = new StringReader(command);
Request req = JAXB.unmarshal(commandReader, Request.class);
commandReader.close();
dispatcher.sendRequest(req);
} catch(DataBindingException ex) {
response.sendResponse(SystemMessageFactory.INVALID);
response.sendResponse(SystemMessageFactory.SOCKET_SHUTDOWN);
}
}
} catch (SocketException e) {
System.out.println("Socket Exception");
} catch (IOException e) {
Logger.getLogger("server").log(Level.SEVERE,
"Error reading the command input of the client!", e);
}
}
}
When the peer abruptly shuts down the socket, the connection reset is sent. The stack trace is:
16.07.2013 1:39:51 EntryPoint run
SEVERE: Error reading the command input of the client!
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at blood.steel.server.EntryPoint.run(EntryPoint.java:36)
at java.lang.Thread.run(Thread.java:662)
How is it possible? I am catching it twice! SocketException is caught in its own catch-clause and in IOException catch clause. But nothing happens! It does not catch the socket exception. How can I handle it and what is the cause of such behaviour?
Either the SocketExceptioon is not the one in java.net. Check your imports.
Or you are not running the code you think you are.
Related
I am working on a chat app in Java and so far everything works all right except that when a client disconnects and a message is send by other client this error pops out:
java.net.SocketException: Software caused connection abort: socket write error
at java.base/java.net.SocketOutputStream.socketWrite0(Native Method)
at java.base/java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:110)
at java.base/java.net.SocketOutputStream.write(SocketOutputStream.java:150)
at java.base/java.io.DataOutputStream.write(DataOutputStream.java:107)
at java.base/java.io.DataOutputStream.writeUTF(DataOutputStream.java:401)
at java.base/java.io.DataOutputStream.writeUTF(DataOutputStream.java:323)
at com.terkea/com.terkea.system.server.ClientThread.run(ClientThread.java:65)
at java.base/java.lang.Thread.run(Thread.java:835)
This is my server Thread:
#Override
public void run() {
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
try {
String input = in.readUTF();
if (Message.fromJSON(input).getUserName().equals("REGISTER")) {
Message specialMessage = Message.fromJSON(input);
specialMessage.setUserName("SERVER");
Client test = Client.fromJSON(specialMessage.getMessage());
test.setIp(socket.getInetAddress().toString());
test.setListening_port(String.valueOf(socket.getPort()));
specialMessage.setMessage(Client.toJSON(test));
input = Message.toJSON(specialMessage);
}
for (ClientThread thatClient : server.getClients()) {
DataOutputStream outputParticularClient = new DataOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeUTF(input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
and the Client:
public void createClient() {
try {
socket = new Socket(getHost(), portNumber);
DataInputStream in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
Message registerclient = new Message("REGISTER", Client.toJSON(getClient()));
out.writeUTF(Message.toJSON(registerclient));
new Thread(() -> {
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
String input = in.readUTF();
Message inputMessage = Message.fromJSON(input);
if (inputMessage.getUserName().equals("SERVER")) {
System.err.println(Client.fromJSON(inputMessage.getMessage()));
allClientsConnected.add(Client.fromJSON(inputMessage.getMessage()));
} else {
chat.add(inputMessage);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
The error corresponds to outputParticularClient.writeUTF(input);
My goal is to get rid of this error and also if possible could anybody tell me a way to check when a client disconnects? I've found some similar questions over here and their solution was to check if (socket.getInputStream().read()!=-1)
but when I do that the whole program freezes and the GUI stops working.
You may want to look into expanding upon your special message functionality, and instead of using the username to pass "REGISTER" use something like messageType in order to do so. This way you can configure handlers based on type to do a number of things. For example things like:
MessageType { REGISTER, UNREGISTER, READ_RECEIPT, ... }
You can then have things like:
RegisterHandler {}
UnregisterHandler{}
and eventually expand them to have some features like facebook/whatsapp (/ICQ haha):
TypingHandler {} // Other user gets a message saying that I am typing to them
From here, you can implement the UNREGISTER to do what you want. Like the first comment says, you should catch the SocketException and manually unregister that client so it doesn't happen anymore. But you should also try to pre-emptively send an
{
messageType: UNREGISTER,
from: Client1
to: server|null,
data: {}
}
so that your server can remove it before the exception occurs. This would also let you handle Offline messages, if that's something you're interested in.
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.
I am creating a socket to a server in java and after the socket is connected it creates a new thread which can access the socket input and output stream and this thread then blocks and processes the input lines when they come in.
I understand that the readln method on the BufferedReader will return null when the input stream ends. This doesn't necessarily mean that the socket is closed though does it? What does this mean? So I would then want to run the close method on the socket to close it nicely.
I also understand that the readln method can throw an IOException and that this is thrown after the close method is called on a socket if it is currently blocking. When else can this be thrown? Could the socket still be open after this is thrown or would it always be closed and ready for garbage collection etc.
This is the code I have at the moment and I don't really know how to handle disconnects properly. At the moment I think this could end up in a deadlock if the disconnect method is called whilst the socket is waiting for a line because disconnect will call close on the socket. This will then throw the IOException on readLine and this will then result in that catch block calling disconnect again.
public class SocketManager {
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private String ip;
private int port;
private Object socketLock = new Object();
public SocketManager(String ip, int port) {
this.ip = ip;
this.port = port;
}
public void connect() throws UnableToConnectException, AlreadyConnectedException {
synchronized(socketLock) {
if (socket == null || socket.isClosed()) {
throw (new AlreadyConnectedException());
}
try {
socket = new Socket(ip, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
throw (new UnableToConnectException());
}
new Thread(new SocketThread()).start();
}
}
public void disconnect() throws NotConnectedException {
synchronized(socketLock) {
if (isConnected()) {
throw (new NotConnectedException());
}
try {
socket.close();
} catch (IOException e) {}
}
}
public boolean isConnected() {
synchronized(socketLock) {
return (socket != null && !socket.isClosed());
}
}
private class SocketThread implements Runnable {
#Override
public void run() {
String inputLine = null;
try {
while((inputLine = in.readLine()) != null) {
// do stuff
}
if (isConnected()) {
try {
disconnect();
} catch (NotConnectedException e) {}
}
} catch (IOException e) {
// try and disconnect (if not already disconnected) and end thread
if (isConnected()) {
try {
disconnect();
} catch (NotConnectedException e1) {}
}
}
}
}
}
I basically want to know the best way of achieving the following:
Writing a connect method that connects to a socket and starts a separate thread listening for input.
Writing a disconnect method that disconnects from the socket and terminates the thread that's listening for input.
Handling the scenario of the connection to the remote socket being broken.
I have read through the java tutorial on sockets but in my opinion it doesn't really cover these in much detail.
Thanks!
When I said that it could end up as a deadlock I think I was wrong.
What would happen is:
disconnect() called whilst in.readLine() blocking
socket.close() executed.
in.readline() throws IOException.
I was then thinking that the exception handler in the SocketThread would call disconnect whilst disconnect is waiting for that exception to finish. It wouldn't matter through because they are both different threads so the code in disconnect() would continue whilst the exception is being caught in the SocketThread. The SocketThread would then call disconnect() but would then have to wait until the first instance of disconnect() finished. Then disconnect() would execute again but would get the NotConnectedException thrown which would be caught in the SocketThread and nothing would happen. The SocketThread would exit and that's the wanted result.
However I have looked into the socket class and it also contains these methods:
shutdownInput()
shutdownOutput()
shutdownInput() sends the end EOF symbol into the input stream meaning in.readline() returns null and the loop exits cleanly. shutdownOutput() sends the TCP termination sequence informing the server that it's disconnecting.
Calling both of these before socket.close() makes more sense because it means the thread will exit nicely instead of exiting as a result of an exception being thrown which has more overhead.
So this is the modified code:
public class SocketManager {
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private String ip;
private int port;
private Object socketLock = new Object();
public SocketManager(String ip, int port) {
this.ip = ip;
this.port = port;
}
public void connect() throws UnableToConnectException, AlreadyConnectedException {
synchronized(socketLock) {
if (socket == null || socket.isClosed()) {
throw (new AlreadyConnectedException());
}
try {
socket = new Socket(ip, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
throw (new UnableToConnectException());
}
new Thread(new SocketThread()).start();
}
}
public void disconnect() throws NotConnectedException {
synchronized(socketLock) {
if (isConnected()) {
throw (new NotConnectedException());
}
try {
socket.shutdownInput();
} catch (IOException e) {}
try {
socket.shutdownOutput();
} catch (IOException e) {}
try {
socket.close();
} catch (IOException e) {}
}
}
public boolean isConnected() {
synchronized(socketLock) {
return (socket != null && !socket.isClosed());
}
}
private class SocketThread implements Runnable {
#Override
public void run() {
String inputLine = null;
try {
while((inputLine = in.readLine()) != null) {
// do stuff (probably in another thread)
}
// it will get here if socket.shutdownInput() has been called (in disconnect)
// or possibly when the server disconnects the clients
// if it is here as a result of socket.shutdownInput() in disconnect()
// then isConnected() will block until disconnect() finishes.
// then isConnected() will return false and the thread will terminate.
// if it ended up here because the server disconnected the client then
// isConnected() won't block and return true meaning that disconnect()
// will be called and the socket will be completely closed
if (isConnected()) {
try {
disconnect();
} catch (NotConnectedException e) {}
}
} catch (IOException e) {
// try and disconnect (if not already disconnected) and end thread
if (isConnected()) {
try {
disconnect();
} catch (NotConnectedException e1) {}
}
}
}
}
}
In order to be sure that all resources associated with the socket are relased you have to call close() method when you finish work with that socket.
Typical IO exception handling pattern is that you catch it and then perform best efforts to clean everything calling close() method.
So the only thing you have to do is to ensure that you call close() on every socket during it's lifetime.
You're on the right track. I wouldn't use "readline", only raw read, and "do stuff"
should be limited to constructing a queue of received data. Likewise writing replies
ought to be a separate thread that empties a queue of data to be sent.
Despite socket's guarantees of integrity, stuff will go wrong and you'll sometimes receive data that doesn't make sense. There's a crapload of stuff below "read" and "write" and no system is perfect or bug free. Add your own wrapper with checksums at the level of YOUR read and write so you can be sure you're receiving what was intended to be sent.
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.
these are my client and server class but i don't know that why the text received doesn't work in a correct way (it will return something but not the one that I want) also when I close the run part of server i will have these exceptions,please help me.thanks
server side:
final static Vector handlers = new Vector(10);
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ChatHandler(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(
new PrintWriter(socket.getOutputStream(),true));
}
#Override
public void run() {
String line;
synchronized (handlers) {
handlers.addElement(this);
}
try {
while ((line = in.readLine()) != null && !line.equalsIgnoreCase("/quit")) {
for (int i = 0; i < handlers.size(); i++) {
synchronized (handlers) {
ChatHandler handler =
(ChatHandler) handlers.elementAt(i);
handler.out.println(line + "\r");
handler.out.flush();
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
synchronized (handlers) {
handlers.removeElement(this);
}
}
}
}
client side: ( apart of that)
public static synchronized void active() {
String teXt = MainClient.getText();
os.println(teXt);
os.flush();
try {
String line = is.readLine();
setFromServertext("Text recieved:"+line+"\n");
is.close();
is.close();
c.close();
} catch (IOException ex) {
Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex);
}
active method will be called when the user write something on the text area and click on the send button.
stacktrace:
init:
deps-jar:
compile-single:
run-single:
Server is starting...
Server is listening...
Client Connected...
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at ServerNetwork.ChatHandler.run(ChatHandler.java:44)
Client Connected...
Client Connected...
java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at ServerNetwork.ChatHandler.run(ChatHandler.java:44)
BUILD STOPPED (total time: 15 minutes 53 seconds)
This normally happens when the socket is closed, which causes the connection to be aborted
The documentation of close() states:
Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.
Use shutdownOutput() if you want a TCP's normal connection termination.
If shutdownOutput is called at the server, the readLine() at the client will return null, indicating an EOF (end of file). Now the client should call shutdownOutput.