gpt4 book ai didi

android - 在套接字连接中没有得到响应

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:04 24 4
gpt4 key购买 nike

我无法在套接字连接中得到响应,我无法理解代码有什么问题。 我可以使用 ip 地址和端口号建立套接字连接,并且它正在进入

    if (nsocket.isConnected()) {} 

当我尝试使用 telnet 时,我可以获得响应。但是输入还有一些其他参数,例如:

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" }

我不知道如何在我的代码中包含内容类型、长度等连接属性。

代码如下:

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;
}

请帮我找出问题所在。我被严重困住了。请帮我解决这个问题

最佳答案

对于套接字驱动的事件,很难实现很多功能,但有一些(开源)库可以实现这样的任务。考虑使用 Socket.io .

Properties headers = new Properties();
headers.setProperty("Content-Type","application/json"); // your headers
SocketIO socketIO = SocketIO(url, headers);

有关更多信息,请查看 SocketIO docs

编辑

在您给出的示例中,您应该使用 HttpURLConnection当您从服务器获得响应时,您不需要实现套接字。只需 GETPOST 即可使用 HttpURLConnection 获取或推送您的数据。

关于android - 在套接字连接中没有得到响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com