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
Problem: the socket is not able to connect Possible explanations: You are trying to reach a plain WebSocket server. The server is not reachable. The client is not compatible with the version of the server.
Socket errors can be caused by various issues including connectivity problems on the network, client or server computers or due to a firewall, antivirus or a proxy server. This error occurs when the socket connection to the remote server is denied.
If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.
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.
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);
}
}
UPDATE
If you want to set custom header, just should write them to printWriter
.
When you write
writer.print ("GET " + szUrl + " HTTP/1.0\r\n\r\n");
The \r\n\r\n bit is sending a line-feed/carriage-return to end the line and then another one to indicate that there are no more headers. This is a standard in both HTTP and email formats, i.e. a blank line indicates the end of headers. In order to add additional headers you just need to not send that sequence until you're done. You can do the following instead
writer.print ("GET " + szUrl + " HTTP/1.0\r\n");
writer.print ("header1: value1\r\n");
writer.print ("header2: value2\r\n");
writer.print ("header3: value3\r\n");
// end the header section
writer.print ("\r\n");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With