Reading via Socket

1

I'm reading strings sent via socket to a server in Java. I get a line but when it reads it comes with breaking, looking like two lines. What I got should be: 78780103554880201238560006d0d8

But it comes:
7878
0103554880201238560006d0d8

ThecodeI'musingisasfollows:

importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.io.OutputStreamWriter;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;publicclassServidor{publicstaticvoidmain(String[]args)throwsException{ServerSocketm_ServerSocket=newServerSocket(2952);intid=0;while(true){SocketclientSocket=m_ServerSocket.accept();ClientServiceThreadcliThread=newClientServiceThread(clientSocket,id++);cliThread.start();}}}classClientServiceThreadextendsThread{SocketclientSocket;intclientID=-1;booleanrunning=true;ClientServiceThread(Sockets,inti){clientSocket=s;clientID=i;}publicvoidrun(){//System.out.println("Accepted Client : ID - " + clientID + " : Address - " + clientSocket.getInetAddress().getHostName());
    try {
      BufferedReader   in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      PrintWriter   out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
      while (running) {

            String clientCommand = in.readLine();
        byte[] b = clientCommand.getBytes();
        clientCommand = bin2Hex(b);

            System.out.println(clientCommand);
            if (clientCommand.equalsIgnoreCase("quit")) {
              running = false;
              System.out.print("Stopping client thread for client : " + clientID);
            } else {
              out.println(clientCommand);
              out.flush();
            }

    }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


    public static String bin2Hex(byte bytes[]) {
        StringBuffer retString = new StringBuffer();
        for (int i = 0; i < bytes.length; ++i) {
            retString.append(
            Integer.toHexString(0x0100 + (bytes[i] & 0x00FF)).substring(1));
        }
        return retString.toString();
    }


}

I do not have much intimacy with Java, I think it may be the way I read or the way I set the data for reading.

Any help?

    
asked by anonymous 09.12.2015 / 12:51

1 answer

1

The problem seems to be with charset . Force the charset to UTF-8 on the following lines (34, 35):

BufferedReader   in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
PrintWriter   out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"));
    
08.11.2016 / 14:54