Reputation: 877
We have java socket connection application which receives data from gps devices. The problem now at times we received corrupted data and checked on the device logs everything is fine. First BufferedReader was used and suspected to be the culprit. The we moved to inpustream also still having problem. The corruption is at random and not fixed interval. Below is the snippet of codes.
public void run() {
String completeMessage="";
//BufferedReader readerBuffer = null;
InputStream is = null;
BufferedWriter writeBuffer = null;
try {
//readerBuffer = new BufferedReader(new InputStreamReader(sockConn1.getInputStream()));
is = sockConn1.getInputStream();
writeBuffer = new BufferedWriter(new OutputStreamWriter(sockConn1.getOutputStream()));
int readChar=0;
sockConn1.setSoTimeout(120000);
//dbConnection = connectionPool.getConnection();
//dbConnection.setAutoCommit(false);
int readChar
while ((readChar=is.read()) != -1)
{
System.out.println("Char value: "+(char)readChar) ;
if (readChar == '*') {
try {
//writeBuffer.write("@@\r\n\r\n");
//writeBuffer.flush();
//db processing
dbConnection.commit();
}
catch (SQLException ex){
ex.printStackTrace();
try{
dbConnection.rollback();
}
catch (Exception rollback){
rollback.printStackTrace();
}
}
catch (Exception e){
e.printStackTrace(System.out);
try{
dbConnection.rollback();
}
catch (Exception rollback){
rollback.printStackTrace(System.out);
}
}
finally{
try{
if ( dbStmt != null ){
dbStmt.close();
}
}
catch(SQLException ex){
ex.printStackTrace(System.out);
}
}
completeMessage="";
}
}
}
catch (SocketTimeoutException ex){
ex.printStackTrace();
}
catch (IOException ex){
ex.printStackTrace();
}
catch (Exception ex){
ex.printStackTrace();
}
finally{
try{
if ( dbConnection != null ){
dbConnection.close();
}
}
catch(SQLException ex){
ex.printStackTrace();
}
try{
if ( writeBuffer != null ){
writeBuffer.close();
}
}
catch(IOException ex){
ex.printStackTrace(System.out);
}
}
}
Upvotes: 0
Views: 1196
Reputation: 14549
It is not clear what character encoding is used here.
When you deal with character streams then it is nearly always a good idea to explicitly provide the character encoding to en-/decode the byte stream.
In my opinion it is most likely a character encoding issue here. Use the same encoding on both sides and you won't have trouble with Reader/Writer.
Upvotes: 0
Reputation: 109547
There is a problem. You read/write binary data as text:
This is bridged by:
And String to byte is bridged by:
Where charEncoding is an optional parameter, defaulting to the operation system encoding.
With UTF-8, the Unicode multi-byte encoding, you are fast into troubles if done wrong. Also other encodings have problematic bytes.
So do not use Reader/Writer.
The read()
delivers an int, -1 for end-of-file, a byte value otherwise.
It seems your test with read() throws a byte away, and the subsequent read does not test for -1.
Upvotes: 1