I cannot get response in a socket connection and I couldnt understand what is wrong with the code. I could able to establish a socket connection using the ip address and port number, and it is entering into
if (nsocket.isConnected()) {}
When I tried with telnet I could get the response . But the input has some other parameters like:
POST /setMap HTTP/1.1 Host: 192.168.1.1 Content-Type: application/json; charset=utf-8 Content-Length: 1234
{ "cmd":"request_get_file_list","verification":"CVS" }
I dont know how to include the connection properties like content type, length in my code.
Here is the code:
public class WebService { public static String devicelisting() { Socket nsocket; String response = null; try { nsocket = new Socket("192.168.1.1", 6666); if (nsocket.isConnected()) { JSONObject json = new JSONObject(); json.put("cmd", "request_get_file_list"); json.put("verification", "CVS"); Log.i("AsyncTask", "doInBackground: Creating socket"); // nsocket = new Socket(); OutputStreamWriter out = new OutputStreamWriter(nsocket.getOutputStream(), StandardCharsets.UTF_8); out.write(json.toString()); Log.i("Webservice", "json.toString"+json.toString()); InputStream in = new BufferedInputStream(nsocket.getInputStream()); BufferedReader r = new BufferedReader(new InputStreamReader(in)); StringBuilder stringbuilder = new StringBuilder(); String line; while ((line = r.readLine()) != null) { stringbuilder.append(line); Log.i("line", "line.line"+line); } response = stringbuilder.toString(); Log.i("Response", response); } else{ Log.i("Response", "not connected"); } } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return response; }
Please help me to find the issue. I am badly stuck up .Please help me resolve the issue
3 Answers
Answers 1
For socket driven events it is difficult to implement many functions while there are some (open source) libraries to achieve such a task. Consider using Socket.io.
Properties headers = new Properties(); headers.setProperty("Content-Type","application/json"); // your headers SocketIO socketIO = SocketIO(url, headers);
For more information have a look at SocketIO docs
Edit
In your given example you should use HttpURLConnection as you are getting a response from server, you do not need to implement sockets. Simply GET
or POST
to fetch or push your data using HttpURLConnection.
Answers 2
For socket connection in android, you can use this gist file that simply implement socket connection.
public SocketConnection(OnStatusChanged statusChangedListener, OnMessageReceived messageReceivedListener) { mStatusListener = statusChangedListener; mMessageListener = messageReceivedListener; isRunning = true; try { InetAddress serverAddr = InetAddress.getByName(SERVER_IP); mStatusListener.statusChanged(WAITING); socket = new Socket(serverAddr, SERVER_PORT); try { printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); mStatusListener.statusChanged(CONNECTED); bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); while (isRunning) { retrieveMessage = bufferedReader.readLine(); if (retrieveMessage != null && mMessageListener != null) { mMessageListener.messageReceived(retrieveMessage); } else { mStatusListener.statusChanged(DISCONNECTED); } retrieveMessage = null; } } catch (Exception e) { mStatusListener.statusChanged(ERROR); } finally { socket.close(); } } catch (Exception e) { mStatusListener.statusChanged(ERROR); } }
Answers 3
The code is probably stuck in readLine()
because the server still waits for the request's completion.
You could change it to :
// query out.write("POST /setMap HTTP/1.1\r\n"); // headers out.write("Host: 192.168.1.1\r\n"); out.write("Content-Type: application/json; charset=utf-8\r\n"); out.write("Content-Length: " + json.toString().getBytes(StandardCharsets.UTF_8).length + "\r\n"); // end of the headers out.write("\r\n"); // body out.write(json.toString()); // actually send the request out.flush(); Log.i("Webservice", "json.toString"+json.toString());
I think that you are using the wrong tool to make HTTP requests. Sockets are low level network channels, you have to do a lot of things yourself.
You should consider using an HttpURLConnection instead. If possible I strongly suggest to take a even higher level approach, and use something like retrofit2 for example.
0 comments:
Post a Comment