Reputation: 638
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
Upvotes: 9
Views: 2056
Reputation: 638
Thank you very much for every answers. All answeres lead me to right one. I could able to fix that issue , here is the code.
myClient = new Socket("192.168.1.1", 6666);
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("cmd", "request_get_file_list");
jsonObject.put("verification", "CVS");
myClient.setKeepAlive(true);
try {
DataInputStream dis = new DataInputStream(myClient.getInputStream());
DataOutputStream dos = new DataOutputStream(myClient.getOutputStream());
writer = new OutputStreamWriter(dos);//, StandardCharsets.UTF_8)
writer.write(jsonObject.toString());
System.out.println("c");
writer.flush();
dos.flush();
System.out.println("output buffer size:" + dos.size());
char c = (char) dis.read();
while (c != '\0') {
System.out.print(c);
str = str.append(c);
if (dis.available() != 0) {
c = (char) dis.read();
} else break;
}
dos.flush();
System.out.println("String:" + str.toString());
normalLoginResponse = str.toString();
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 1670
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");
Upvotes: 4
Reputation: 17755
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.
Upvotes: 3
Reputation: 2124
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.
Upvotes: 4