A
A
Artur Aralin2014-04-30 12:48:22
Java
Artur Aralin, 2014-04-30 12:48:22

Java Server. How to solve encoding problem?

Good day! There was such a problem: I send a request from the browser to my server and get this in response:
" E TP11
ot oahs: 79
oncin epaie
ah-oto: mxae0
cet ethm,plcto/hm+m,plcto/m;=.,mg/ep **q08
srAet oil/.WnosN .;WW4 plWbi/3.6(HM,lk ek)Crm/4014.3 aai573
Acp-noig zpdfaesc
Acp-agae uR,uq08e-Sq06e;=.
Coi:tf=n
"

What's the problem? I just can't understand!

Server code:

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class Main {
  public static void main(String[] args) {
    ServerSocket server = null; 
    try {
      server = new ServerSocket(7779);
      System.out.println("Server: Start!");
    } catch (IOException e) {
      System.out.println("Server: Port difined!");
      e.printStackTrace();
    }
    
    while (true) {
      StringBuffer sb = new StringBuffer(); //Запрос браузера
      char simbol;
      try {
        Socket clientSocket = server.accept(); //Создаем сокет с клиентом
        InputStream is = clientSocket.getInputStream(); //получаем от него данные
        while(is.read() != -1) { //Записываем посимвольно запрос
          simbol = (char) is.read();
          sb.append(simbol);
        }
        is.close();
        System.out.println(sb.toString()); //выводим в консоль
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kenny4ka, 2014-04-30
@kenny4ka

I will assume that is.read() reads a byte, not a character. A character can be more than 1 byte.
I advise you to use buffered reading:

bufferedInput = new BufferedInputStream(is);
byte[] buffer = new byte[1024];    //
int read;
while((read = bufferedInput.read(buffer)) != -1) {
    System.out.println(read);
}

B
bazarnazar, 2014-08-28
@bazarnazar

Here's how I did it, and everything works fine (although I can only say with certainty about GET requests)

public class TinyHttpd extends Thread {

    public static Logger log = Logger.getLogger(TinyHttpd.class.getName());

    static StatusController statusController;

    @Inject
    public TinyHttpd(StatusController statusControllerNew) {
        super("TinyHttpd");
        statusController = statusControllerNew;
    }

    private volatile boolean active = true;

    private ServerSocket ss;

    public void deactivate() {
        active = false;
        try {
            ss.close();
        } catch (IOException e) {
            log.error(e);
        }
    }

    public void run() {

        try {
            ss = new ServerSocket();
            SocketAddress address = new InetSocketAddress("0.0.0.0", 8080);
            ss.bind(address);
            log.info("Start TinyHttpd");
            while (active) {
                new TinyHttpdConnection(ss.accept()).start();
                log.debug("new connection");
            }
        } catch (IOException e) {
            log.error(e);
        }
        log.info("Stopping TinyHttpd");
    }
}

class TinyHttpdConnection extends Thread {

    private static int threadNum = 0;

    Socket client;

    TinyHttpdConnection(Socket client) throws SocketException {
        super("TinyHttpdConnection-" + ++threadNum);
        this.client = client;
        setPriority(NORM_PRIORITY - 1);
    }

    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    client.getInputStream(), "8859_1"));
            OutputStream out = client.getOutputStream();
            PrintWriter pout = new PrintWriter(new OutputStreamWriter(out,
                    "8859_1"), true);
            String request = in.readLine();
            TinyHttpd.log.debug("Request: " + request);
            StringTokenizer st = new StringTokenizer(request);
            if ((st.countTokens() >= 2) && st.nextToken().equals("GET")) {
                request = st.nextToken();
                //тут логика и анализ токенов
                } else {
                    pout.println("400 Bad Request");
                }
            } else {
                pout.println("400 Bad Request");
            }
            client.close();
        } catch (IOException e) {
            System.out.println("I/O error " + e);
        }
    }
}

Also note that after socket.accept() a new thread is created. I would highly recommend doing this so that more than one client could be processed at the same time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question