I've got a problem to make two applications to send text-data between themselves. The message is transmitted without any problems, the answer is received too. But, there is a lot of a "New line" char in the end of the string send/received on each side. I guess it's because of I'm reading the full buffer; I've tried to remove all Chr(10) and Chr(13); I also tried to trim the string, but it didn't worked.
Here the code I use :
Client Side :
Dim cl As New TcpClient
cl.Connect("127.0.0.1", 2000)
Dim str As NetworkStream = cl.GetStream
Dim HelloInBytes As Byte() = Encoding.UTF8.GetBytes("Hello")
str.Write(HelloInBytes, 0, HelloInBytes.Length)
Dim Buffer(cl.ReceiveBufferSize) As Byte
str.Read(Buffer, 0, cl.ReceiveBufferSize)
Console.WriteLine(Encoding.UTF8.GetChars(Buffer))
Server Side :
Dim srv As New TcpListener(IPAddress.Any, 2000)
srv.Start()
Dim cl As TcpClient = srv.AcceptTcpClient
Dim str As NetworkStream = cl.GetStream
Dim buf(cl.ReceiveBufferSize) As 开发者_StackOverflow社区Byte
str.Read(buf, 0, cl.ReceiveBufferSize)
Dim res As Byte() = Encoding.UTF8.GetBytes("World")
str.Write(res, 0, res.Length)
Is there a way to "clean" the received string ?
Thanks for help.
EDIT : Solution : It Works with Harzcle solution. I found another solution which is to use this function on the received string :
Public Function CleanString(ByRef Str As String)
Return Str.Replace(Encoding.UTF8.GetChars({0, 0, 0, 0}), Nothing)
End Function
UTF8 works on 4 bytes, and when I read the stream and I put it into a buffer, if there is no char, the 4 bytes stay on a 0 value.
Use Flush() after you write into the buffer
str.Write(HelloInBytes, 0, HelloInBytes.Length)
str.Flush()
And
str.Write(res, 0, res.Length)
str.Flush()
Edit:
You can use a delimiter or something like that.
Client side:
Dim delimiterChar as Char = "|"
Dim out As Byte() = System.Text.Encoding.UTF8.GetBytes(txtOut.Text + delimiterChar)
server.Write(outStream, 0, outStream.Length)
server.Flush()
And Server side:
Dim delimiterChar as Char = "|"
Dim Stream As NetworkStream = clientSocket.GetStream()
Stream.Read(bytesFrom, 0, CInt(client.ReceiveBufferSize))
Dim data As String = System.Text.Encoding.UTF8.GetString(bytesFrom)
data = data.Substring(0, data.IndexOf(delimiterChar)) 'From 0 to delimiter
This will remove all null characters at the end of the received string
client_content = client_content.Replace(Chr(0), Nothing)
To remove new lines:
client_content = client_content.Replace(vbLf, Nothing)
精彩评论