简体   繁体   English

TCP:如何从Android客户端中的Vb.net服务器获取响应?

[英]TCP: How to get response from Vb.net server in Android Client?

This is not a possible duplicate. 这是不可能的重复。 No answer on this site adequately answers or solves my issue. 该站点上没有任何答案可以充分回答或解决我的问题。

I am trying to connect to a VB.NET server via TCP socket and get response in Android application. 我正在尝试通过TCP套接字连接到VB.NET服务器,并在Android应用程序中获得响应。 The response is always null as string or -1 as bytes. 响应始终为null(字符串)或-1(字节)。

I have to connect and get a response for multiple platforms but for the moment I just want to focus on the Android app. 我必须连接并获得针对多个平台的响应,但此刻我只想专注于Android应用程序。 Maybe if I figure it out, it will be easier to move forward to other platforms. 也许如果我弄清楚了,向其他平台迁移会更容易。

I do not have access to edit any code in the VB.NET live server. 我无权编辑VB.NET实时服务器中的任何代码。 There system is pretty old and has been only sending responses to other Windows clients up until now. 那里的系统相当老,到目前为止一直只向其他Windows客户端发送响应。

Here is my Android client. 这是我的Android客户端。 It is inside a background task which is called from the mainActivity. 它位于从mainActivity调用的后台任务中。 The below command string should return coordinates in the form of a string from the server. 下面的命令字符串应以字符串形式从服务器返回坐标。 Nothing is returned. 什么也没退。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {


    public static void sendMessage() throws IOException, InterruptedException {

        Socket socket = null;
        String host = "";
        int port = ;
        PrintStream stream = null;
        String command="";

        try {
            Socket s = new Socket(host,port);
            System.out.println("Socket created");

            //outgoing stream redirect to socket
            OutputStream out = s.getOutputStream();

            PrintWriter output = new PrintWriter(out);
            output.println(command);
            output.flush();
            System.out.println("command sent");
            BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));

            //read line(s)
            System.out.println("Getting response:");
            String st = input.readLine();
            System.out.println("Response : " + st);
            //Close connection
            s.close();
        }

        catch (UnknownHostException e) {
            System.out.println("Don't know about host : " + host);
            e.printStackTrace();
            System.exit(1);
        }

        catch (IOException e) {
            System.out.println("Couldn't get I/O for the connection to : " + host);
            e.printStackTrace();
            System.exit(1);
        }

    }
}

A developer also sent me a test client in VB which connects, sends and recieves without problem 开发人员还向我发送了VB中的测试客户端,该客户端可以毫无问题地进行连接,发送和接收

Here is a class of a VB:NET Dummy server project the developer has sent me to see how the live server is setup code-wise. 这是开发人员发送给我的VB:NET Dummy服务器项目的类,以了解如何通过代码方式设置实时服务器。 I can see it gets the string as unicode but I am not confident in VB to know where my Java code is going wrong. 我可以看到它以unicode的形式获取字符串,但是我对VB不确定我的Java代码哪里出了问题。

When I open the project and start the server on localhost I cant connect to it from the java client anyway. 当我打开项目并在本地主机上启动服务器时,无论如何我都无法从Java客户端连接到它。 Then I have written another client in PHP, same problem, connection established but no response. 然后,我用PHP编写了另一个客户端,同样的问题,建立了连接,但是没有响应。 I downloaded a socket tester software but it also can connect but does not get a response. 我下载了一个套接字测试仪软件,但它也可以连接但没有响应。

Option Explicit On
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports Microsoft.VisualBasic

Imports System.Net.Dns
Imports System.Text.UnicodeEncoding
Imports System.Threading
Imports System.Data.SqlClient



Public Enum glenConnectionType
    ConstantConnection = 1
    ConnectOnDemand = 2
    AsyncConnection = 3
End Enum

Public Class clsDynaListner
    Public tcpServer As Socket
    Public tcpClient As Socket
    Public tcpPort As Integer
    Public tcpBilnr As Integer ' was shared SHOULD PROB BE INITIALISED TO 0
    Public ThreadClient As Thread
    Public LastKontakt As Date = Nothing
    Public ConActive As Boolean = False
    Private tcpClientEndPoint As System.Net.IPEndPoint
    Private bCommandLength(15), bReplyLength(15) As Byte
    Private iCommandLength, iReplyLength As Integer
    Private sReplyLength As String
    Private sCommand, sReply As String
    Private theCommandBytes() As Byte
    Private theReplyBytes() As Byte
    Private Const AsyncMaxBytes As Integer = 600000 '1024
    Public Shared AsyncData As String = Nothing

    Public Sub New(ByVal currentTCPPort As Integer, ByVal theConnectionType As glenConnectionType)
        tcpPort = currentTCPPort
        tcpClientEndPoint = New System.Net.IPEndPoint(System.Net.IPAddress.Any, tcpPort)

        'Select Case theConnectionType
        '    Case glenConnectionType.ConstantConnection
        '        ThreadClient = New Threading.Thread(AddressOf ListenForConstantConnection)
        '    Case glenConnectionType.ConnectOnDemand

        ThreadClient = New Threading.Thread(AddressOf ListenForConnectOnDemand)

        '    Case glenConnectionType.AsyncConnection
        'ThreadClient = New Threading.Thread(AddressOf ListenForAsyncConnection)
        'End Select

        ThreadClient.Start()
    End Sub


Private Sub ListenForConnectOnDemand()
        While (True)
            Try
                tcpServer = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                tcpServer.SendBufferSize = TCP_BUFFER_SIZE
                tcpServer.ReceiveBufferSize = TCP_BUFFER_SIZE
                tcpServer.Blocking = True
                tcpServer.Bind(tcpClientEndPoint)
                tcpServer.Listen(0)
                tcpClient = tcpServer.Accept

                tcpClient.SendBufferSize = TCP_BUFFER_SIZE
                tcpClient.ReceiveBufferSize = TCP_BUFFER_SIZE

                ' Find out how big the command is going to be
                tcpClient.Receive(bCommandLength)
                iCommandLength = CType(Unicode.GetString(bCommandLength), Integer)

                ' Bring that command to daddy
                Array.Resize(theCommandBytes, iCommandLength + 1)
                tcpClient.Receive(theCommandBytes)
                sCommand = Unicode.GetString(theCommandBytes)
                gInMessage = sCommand

                ' Get the reply
                sReply = "Response:"
                gOutMessage = sReply

                ' Inform the controller of the length of the reply transmission
                iReplyLength = (sReply.Length * 2) - 1
                sReplyLength = iReplyLength.ToString.PadLeft(8, "0")
                bReplyLength = Unicode.GetBytes(sReplyLength)
                tcpClient.Send(bReplyLength)

                ' Send the reply data
                Array.Resize(theReplyBytes, iReplyLength + 1)
                theReplyBytes = Unicode.GetBytes(sReply)
                tcpClient.Send(theReplyBytes)

                Array.Clear(theCommandBytes, 0, theCommandBytes.Length)
                Array.Clear(theReplyBytes, 0, theReplyBytes.Length)

                tcpClient.Close()
                tcpServer.Close()
                tcpClient = Nothing
                tcpServer = Nothing

            Catch ex1 As Exception
                Try
                    tcpClient.Close()
                    tcpServer.Close()
                    tcpClient = Nothing
                    tcpServer = Nothing
                    ' ErrMessage = "LisForContr :" & tcpPort.ToString & ex1.Message
                Catch
                End Try
            End Try
        End While

    End Sub

    Protected Overrides Sub Finalize()
        Try
            tcpServer.Close()
            ThreadClient.Abort()
        Catch
        End Try

        MyBase.Finalize()
    End Sub

End Class

I have been working with this for a while. 我已经为此工作了一段时间。 The apps I have built are complete for PHP Web App, Android Native, and iPhone Native. 我构建的应用程序对于PHP Web App,Android Native和iPhone Native来说都是完整的。 The problem is only getting the response from the VB server. 问题仅在于从VB服务器获得响应。

Would like some help to push me in the right direction. 想要一些帮助将我推向正确的方向。

Also I enquired with the developers if the response has a line-break. 我也询问开发人员响应是否有换行符。 It does not and it does seem they are willing to mess with the code as it served there purpose for many many years. 事实并非如此,而且看起来他们确实愿意将代码弄乱,因为多年来一直在这里使用。 So I have to find away around that. 所以我必须找到解决办法。

If you need me to provide more info just ask. 如果您需要我提供更多信息,请询问。

To send to a VB.NET server from Java you must send the string as unicoded bytes. 要从Java发送到VB.NET服务器,必须将字符串作为未编码的字节发送。 Send the length at the bytes to expect first and then send the primary data and flush. 首先发送期望的字节长度,然后发送主要数据并刷新。 You have to know exactly what the server is expecting in order to format and encode the data accordingly in preparation to send it. 您必须确切地知道服务器期望什么,以便对数据进行相应的格式化和编码以准备发送数据。

I was able to successfully fix my issue after debugging VB client and server. 调试VB客户端和服务器后,我能够成功解决问题。 This client will process byte arrays, stream advanced sql commands and get the response. 该客户端将处理字节数组,流式传输高级sql命令并获取响应。 The update will be getting xml table data. 更新将获取xml表数据。 Anyone who wants to input how to make this client better. 任何想输入如何使这个客户更好的人。 You are welcome. 别客气。

Updated my java client as follows. 更新了我的Java客户端,如下所示。

/**
 * MR-TCP Java & VB.NET DataExchange Client 0.95 - Maze Runner 2015
 */

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client {

    public static String sendCommand(String commandString, Boolean IsID) throws IOException, InterruptedException {

        String host;
    int port;
    String command;
    byte[] commandBytes;
    String commandLength;
    byte[] cmdLengthBytes;
    Socket s;
    DataOutputStream stream;
    String dataString = "";

    host = ""; //
    port = 0; // 

    command = commandString;
    commandBytes = command.getBytes("UTF-16LE"); // returns byte[18]

    if(IsID){
        commandLength = "00000021";
        cmdLengthBytes = commandLength.getBytes("UTF-16LE"); 
    } else {
        String iCommandLength = command; // Get the command length
        cmdLengthBytes = iCommandLength.getBytes("UTF-16LE");
        int commandNewLength = cmdLengthBytes.length-1;
        String newLength = "0000" + String.valueOf(commandNewLength);
        cmdLengthBytes = newLength.getBytes("UTF-16LE");

    }

    try {
        s = new Socket(host, port); // Connect to server

        //Send the command to the server
        stream = new DataOutputStream(s.getOutputStream()); // get ready to send

        stream.write(cmdLengthBytes); // tell the server how many bytes to expect

        System.out.println("Command length sent");

        stream.write(commandBytes); // Send the command to papa...

        stream.flush(); // guaranteed sending

        System.out.println("Command sent");

        //Receive the command from the server.
        DataInputStream is = new DataInputStream(s.getInputStream()); // get ready to receive

        ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // prepare to get array

        int nRead;
        byte[] data = new byte[1024];

        while ((nRead = is.read(data, 0, data.length)) != -1) { // read the array byte by byte
            buffer.write(data, 0, nRead);
        }

        byte[] dataBytes =  buffer.toByteArray(); // get complete array

        dataString = buffer.toString("UTF-16LE").substring(8); // get rid of the array length and convert to string


        stream.close(); // close the dataStream

        s.close(); // close the connection

        System.out.println("Disconnected");

    } catch (IOException e){
        e.printStackTrace();
    }

    System.out.println("Function Complete");

    System.out.println("Server response:" + dataString);


    return dataString;

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM