gpt4 book ai didi

java - 通过 TCP 发送大字符串时丢失数据。 (客户端服务器)

转载 作者:行者123 更新时间:2023-12-01 15:22:56 24 4
gpt4 key购买 nike

我有一个客户端/服务器应用程序,其中服务器在 java 中,客户端在 Vb.net 中。

当我从客户端发送大字符串到服务器时,我没有收到完整的文本。请帮忙。

下面附有代码。

客户端--VB.net-

      Try
Dim clientSocket As New System.Net.Sockets.TcpClient()

' msg("Client Started")
clientSocket.Connect(StrIP_Add, intPort)
clientSocket.SendBufferSize=104857600
'6511 6522
' Label1.Text = "Client Socket Program - Server Connected ..."

Dim serverStream As NetworkStream = clientSocket.GetStream()
Dim outStream(104857600) As Byte

' MsgBox(strValidator.Trim.Length)

outStream = System.Text.Encoding.ASCII.GetBytes(strValidator.Trim)
' Dim outStream As Byte() = "sdsfd"
System.Threading.Thread.Sleep(2000)
serverStream.Write(outStream, 0, outStream.Length)
System.Threading.Thread.Sleep(2000)
serverStream.Flush()

Dim inStream(104857600) As Byte
serverStream.Read(inStream, 0, outStream.Length) '104857600) ' CInt(clientSocket.ReceiveBufferSize))
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)
' msg("Data from Server : " + returndata)
clientSocket.Close()

Catch ex As Exception
' VikUcMsg.AddMessage("<b><u>" & Page.Title & "</u></b><br><br>" & "No Connectivity on the port :" & intPort, enmMessageType.Error)


End Try
<小时/>

服务器——Java

BufferedInputStream RecievedBuffer = new BufferedInputStream(
TCPIP_Client_SOCKET.getInputStream());
InputStreamReader RecievedInputStreamReader = new InputStreamReader(
RecievedBuffer);

System.out.println(RecievedBuffer.toString().length());
//char[] RecievedChars = new char[TCPIP_Client_SOCKET
//.getReceiveBufferSize()];

char[] RecievedChars = new char[100000];
//Thread.sleep(5000);
RecievedInputStreamReader.read(RecievedChars);
//Thread.sleep(5000);
String strRecievedData=null;
//Thread.sleep(5000);
strRecievedData = new String( RecievedChars ).trim();
//strRecievedData = RecievedChars.;
Thread.sleep(5000);
if (strRecievedData!=null)
{
System.out.println(strRecievedData);
}

strRecievedData 始终只有 8192。

最佳答案

简单的回答是,从套接字读取数据时必须循环,因为无法保证每次尝试读取时会收到多少字节。

伪代码:

while (!msgCompleted && !overallTimeout)
{
bytesRead = netstream.Read(readBuffer);

if (bytesRead > 0)
{
// here append readBuffer to msgBuffer from offset to offset+bytesRead

offset += bytesRead // update offset so you can keep appending

// inspect the msgBuffer to see if the message is completed
}

}

总而言之,您的代码中还存在许多其他问题。例如...

您在此处分配 104857601(而不是 104857600)字节缓冲区:

Dim outStream(104857600) 作为字节

然后丢弃该缓冲区并用 strValidator 返回的任何内容替换该缓冲区:

outStream = System.Text.Encoding.ASCII.GetBytes(strValidator.Trim)

仅仅为了替换它而预先分配它是没有意义的。

另一个...

您分配一定长度的输入缓冲区:

Dim inStream(104857600) 作为字节

但是然后使用不同缓冲区的长度读入该缓冲区:

serverStream.Read(inStream, 0, outStream.Length)

根据长度的不同,这很容易出错。

您还需要像 Java 读取一样循环执行此 VB 读取。

关于java - 通过 TCP 发送大字符串时丢失数据。 (客户端服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10613226/

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