android - Android 应用程序与 Visual Studio 终端之间的 TCP 连接
问题描述
我正在尝试以我的 android 应用程序作为客户端来实现 tcp 通信。该服务器已经在 Visual Studio 中使用库在 c++ 中实现WS2tcpip.h
。然后客户端应该发送一个字符串供服务器接收,然后再次返回。我已经使用同样在 Visual Studio 中实现的客户端测试了服务器,并且我能够发送服务器接收然后返回的消息。见下图
更新代码
控制片段.java
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_control, container, false); //This inflates the control_fragment layout to this java class.
startBtn = view.findViewById(R.id.startBtn);
socketString = view.findViewById(R.id.socketString);
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BackgroundTask b = new BackgroundTask();
b.execute("Hello");
}
});
return view;
}
class BackgroundTask extends AsyncTask<String, Void, Void> {
Socket s;
DataOutputStream dos;
String ip, message;
@Override
protected Void doInBackground(String... params) {
ip = "192.168.87.103";
message = params[0];
try {
s = new Socket(ip, 9700);
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(message);
dos.close();
s.close();
} catch (UnknownHostException e) {
Log.d(TAG, "doInBackground: UnknownHostException" + e.toString());
} catch (IOException e) {
Log.d(TAG, "doInBackground: IOexception" + e.toString());
} catch (Exception e) {
Log.d(TAG, "doInBackground: Exception" + e.toString());
}
return null;
}
}
现在我看到客户端在我按下按钮后连接到服务器,但它立即断开连接,如下图所示。
我认为错误在下面的代码中。似乎服务器没有收到任何东西。
int bytesReceived = recv(clientSocket, buf, 4096, 0); //Returns the number of bytes received
if (bytesReceived == SOCKET_ERROR)
{
cerr << "Error in recv(). Qutting" << '\n' << endl;
closesocket(clientSocket);
WSACleanup();
}
if (bytesReceived == 0)
{
cout << "Client disconnected " << '\n' << endl;
break;
}
我已经在清单中包含了互联网许可。希望这是有道理的,并提前感谢您。
解决方案
推荐阅读
- json - 如何停止 JSON 路径返回对象
- spring-boot-maven-plugin - MappingException:无法确定类型:org.springframework.boot.configurationprocessor.json.JSONObject
- python-3.x - Termux 中的 Firefox Selenium
- r - 更快地实现对所有可能组合的过滤
- vba - VBA 中是否有任何 C 样式的字符串格式?
- python - 如何使用 docker 依赖项运行 python 程序(或其他 cmd)?
- python - 在 seaborn 计数图中生成子集
- react-native - 无效的解构不可交互实例的尝试
- c# - 有没有一种从结构中获取随机值的有效方法?
- git - “git log --follow”总是忽略合并提交