首页 > 解决方案 > Android 应用程序与 Visual Studio 终端之间的 TCP 连接

问题描述

我正在尝试以我的 android 应用程序作为客户端来实现 tcp 通信。该服务器已经在 Visual Studio 中使用库在 c++ 中实现WS2tcpip.h。然后客户端应该发送一个字符串供服务器接收,然后再次返回。我已经使用同样在 Visual Studio 中实现的客户端测试了服务器,并且我能够发送服务器接收然后返回的消息。见下图

TCP客户端和服务器通信

更新代码

控制片段.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;
    }
}

现在我看到客户端在我按下按钮后连接到服务器,但它立即断开连接,如下图所示。

TCP 连接

我认为错误在下面的代码中。似乎服务器没有收到任何东西。

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

我已经在清单中包含了互联网许可。希望这是有道理的,并提前感谢您。

标签: androidvisual-studiotcpcommunication

解决方案


推荐阅读