length of character in redis value - vb.net

hay, I'm new in Redis. I want to create my own redis-cli with vb.net. I found a reference like this
Imports System.Net.Sockets
Imports System.Text
Module Module1
Sub Main()
Dim stream As NetworkStream
Dim client As TcpClient
Dim bytes() As Byte
Dim result As String
Try
client = New TcpClient()
client.Connect("127.0.0.1", 6379)
stream = client.GetStream()
bytes = Encoding.UTF8.GetBytes("keys *" & vbCrLf)
stream.Write(bytes, 0, bytes.Length)
stream.Flush()
ReDim bytes(client.ReceiveBufferSize)
stream.Read(bytes, 0, bytes.Length)
result = Encoding.UTF8.GetString(bytes)
result = Left(result, InStrRev(result, vbCrLf))
Console.WriteLine("Result:" + result)
Catch ex As Exception
Console.WriteLine("Error:" + ex.ToString())
End Try
End Sub
End Module
actually it works. but why the result always gives me a length of character? where I can delete or remove it? the result is like this:
yeah, because I just have 1 key

Related

Chrome Native Messaging Host VB.Net

I have had a hard time finding any support for Chrome Native Messaging Hosts in VB.Net, after much trial and error I have put together something that works for a single message at a time. However I have not been able to get the
While OpenStandardStreamIn() IsNot Nothing
part to work. If anyone has any suggestions...
OTHERWISE THIS CODE WORKS GREAT, for anyone else like me looking for a VB.Net Native Message Host:
Also, this uses Newtonsoft.Json Lib for JSON serializing...
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Module Module1
Public Sub Main(ByVal args As String())
'create response as an array so it can be easily converted JSON
Dim ResponseString() As String = {""}
' get input from chrome extension
Dim InputString As String = OpenStandardStreamIn()
' Do whatever you want with Input, then prepare Response
ResponseString(0) = DO_SOMETHING(InputString)
' Send Response to Chrome
OpenStandardStreamOut(ResponseString)
End Sub
Public Function OpenStandardStreamIn() As String
Dim MsgLength As Integer = 0
Dim InputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {} 'first 4 bytes are length
Dim StdIn As System.IO.Stream = Console.OpenStandardInput() 'open the stream
StdIn.Read(LenBytes, 0, 4) 'length
MsgLength = System.BitConverter.ToInt32(LenBytes, 0) 'convert length to Int
Dim Buffer As Char() = New Char(MsgLength - 1) {} 'create Char array for remaining bytes
Using Reader As System.IO.StreamReader = New System.IO.StreamReader(StdIn) 'Using to auto dispose of stream reader
While Reader.Peek() >= 0 'while the next byte is not Null
Reader.Read(Buffer, 0, Buffer.Length) 'add to the buffer
End While
End Using
InputData = New String(Buffer) 'convert buffer to string
Return InputData
End Function
Private Sub OpenStandardStreamOut(ByVal ResponseData() As String) 'fit the response in an array so it can be JSON'd
Dim OutputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {} 'byte array for length
Dim Buffer As Byte() 'byte array for msg
OutputData = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseData) 'convert the array to JSON
Buffer = System.Text.Encoding.UTF8.GetBytes(OutputData) 'convert the response to byte array
LenBytes = System.BitConverter.GetBytes(Buffer.Length) 'convert the length of response to byte array
Using StdOut As System.IO.Stream = Console.OpenStandardOutput() 'Using for easy disposal
StdOut.WriteByte(LenBytes(0)) 'send the length 1 byte at a time
StdOut.WriteByte(LenBytes(1))
StdOut.WriteByte(LenBytes(2))
StdOut.WriteByte(LenBytes(3))
For i As Integer = 0 To Buffer.Length - 1 'loop the response out byte at a time
StdOut.WriteByte(Buffer(i))
Next
End Using
End Sub
End Module
From the Chrome Extension, open a connection, send a message, and once a response is received the host will close. Check our Chrome's Dev page for a sample app/extension: https://developer.chrome.com/apps/nativeMessaging
I hope this helps somebody, and please let me know if you make any improvements!
Sub Main() ' Recursive Version
Try
Dim stdin As Stream = Console.OpenStandardInput()
Dim stdout As Stream = Console.OpenStandardOutput()
Dim MsgLength As Integer = 0
Dim InputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {}
stdin.Read(LenBytes, 0, 4)
MsgLength = BitConverter.ToInt32(LenBytes, 0)
Dim Buffer As Byte() = New Byte(MsgLength - 1) {}
stdin.Read(Buffer, 0, Buffer.Length)
InputData = Encoding.UTF8.GetString(Buffer)
Dim Str As String = Newtonsoft.Json.JsonConvert.SerializeObject("[" & Now & "] Arrrr!")
Dim buff() As Byte = Encoding.UTF8.GetBytes(Str)
stdout.Write(BitConverter.GetBytes(buff.Length), 0, 4)
stdout.Write(buff, 0, buff.Length)
Main()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Oh, Snap!")
End Try
End Sub

VB.net TCP Non-Blocking State

I have code that sending string from client to server with TCP Connection.
But i dont know how to convert it to NonBlocking TCP State Connection.
i have try to put socket.Blocking = FALSE, but that code give me an error.
Socket Error Code: 10035
Exception Title: A non-blocking socket operation could not be completed immediately
Heres my code for sending string from client to server.
Server Code :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim soket As Socket
Sub Main()
Try
Dim alamatIP As IPAddress = IPAddress.Parse("127.0.0.1")
Dim tcpListener As New TcpListener(alamatIP, 8000)
'soket.Blocking = False - THIS WILL GIVE ME AN ERROR
tcpListener.Start()
System.Console.WriteLine("Server port 8000...")
Dim myendpoint As IPEndPoint
myendpoint = CType(tcpListener.LocalEndpoint, IPEndPoint)
System.Console.WriteLine("IP : " + myendpoint.Address.ToString + " and port is " + myendpoint.Port.ToString)
System.Console.WriteLine("Waiting for connection !")
soket = tcpListener.AcceptSocket()
myendpoint = CType(soket.RemoteEndPoint(), IPEndPoint)
System.Console.WriteLine("Receiving from " + myendpoint.Address.ToString())
Dim bitData(100) As Byte
Dim newString As String = ""
Do
Try
Dim size As Integer = soket.Receive(bitData)
newString = Encoding.ASCII.GetString(bitData)
Console.WriteLine(newString)
Array.Clear(bitData, 0, bitData.Length)
Catch ex As Exception
Console.Write(ex.ToString())
End Try
Loop While newString <> "exit"
soket.Close()
tcpListener.Stop()
Catch ex As Exception
Console.WriteLine("Error ..." + ex.ToString())
End Try
Console.ReadLine()
End Sub
End Module
Client Code :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Imports System.Threading
Module Module1
Sub Main()
Try
Dim tcpClient As New TcpClient 'creating the client
Console.WriteLine("Connecting....")
tcpClient.Connect("127.0.0.1", 8000) 'connecting the client the server
'port is same as in the server
Console.WriteLine("Connected")
Console.WriteLine("Enter the string to be transmitted : ")
Dim strMessage As String
Dim stm As Stream
Dim counter As Integer = 0
Do
stm = tcpClient.GetStream() 'getting the stream of the client
Dim ascenc As New ASCIIEncoding
strMessage = Console.ReadLine()
Dim byteData() As Byte = ascenc.GetBytes(strMessage)
Console.WriteLine("Transmitted ")
stm.Write(byteData, 0, byteData.Length())
Loop While strMessage <> "exit"
tcpClient.Close() 'closing the connection
Catch ex As Exception
Console.WriteLine("Error..." + ex.StackTrace.ToString()) 'writing the exception into the console
End Try
End Sub
End Module
Thanks for any help.
When you attempt to read from a non-blocking socket or write to it and the operation cannot be completed right now, then the socket is supposed to signal an error. In VB it means it is supposed to raise an exception. For example, this happens when your machine hasn't received any data but you try to Read something.
Before trying an operation on a non-blocking socket, call Select or Poll in order to make sure it is ready for the operation.

Send Hex Decimal over TCP / IP

Im Developing a client to send information to a specific server. And the server accept only a spesific data from the client. The Data is "163130303030323030fc". I have converted it into Ascii as
"SYN10000200ü"
it works except "SYN". The "SYN" has to be converted to "16" to make it happen. But when I use the code Encoding.Default.GetBytes("<SYN>10000200ü") the result receive as
3c53594e3e3130303030323030fc
The code Im Using Is as follows ,
Dim tcpClient As New System.Net.Sockets.TcpClient()
Try
tcpClient.Connect("192.168.18.6", 60010)
Dim networkStream As NetworkStream = tcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
Dim sendBytes As Byte() = Encoding.Default.GetBytes("<SYN>10000200ü")
networkStream.Write(sendBytes, 0, sendBytes.Length)
Do
Loop Until networkStream.DataAvailable
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
Dim returndata As String = Encoding.ASCII.GetString(bytes)
TextBox1.Text &= returndata
tcpClient.Close()
Else
If Not networkStream.CanRead Then
tcpClient.Close()
Else
If Not networkStream.CanWrite Then
tcpClient.Close()
End If
End If
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
It ok if there's a way to send the data in hex without encording to ascii
Your kind Consideration is highly appreciated !
If you need the String to be sent as text, and not hex, the SYN-character would convert to char 22. Refer to the DEC/Decimal column in an ASCII table.
Try doing this:
Encoding.ASCII.GetBytes(ChrW(22) & "10000200ü")
Else if it must be sent as HEX, just send the hex string as it is:
Encoding.Default.GetBytes("163130303030323030fc")

VB.Net Picturebox "Parameter is not Valid" when get online images

Dim ShowImgWebClient = New WebClient
Dim ImageInBytes As Byte() = ShowImgWebClient.DownloadData("http://ex.domain.com/index.php?checksum=" & lblCheckSum.Text.ToString())
Dim ImageStream As New MemoryStream(ImageInBytes)
Dim CaptchaImg As Image = New Bitmap(ImageStream)
ptbCaptcha.Image = CaptchaImg
I'm use this code for get online captcha to my picturebox name ptbCaptcha.
but when request this image my program show error Parameter is not Valid.
Why this ? and How to make it work ?
This is not the proper way to use MemoryStream.
Here is the example taken from microsoft website :
Imports System
Imports System.IO
Imports System.Text
Module MemStream
Sub Main()
Dim count As Integer
Dim byteArray As Byte()
Dim charArray As Char()
Dim uniEncoding As New UnicodeEncoding()
' Create the data to write to the stream.
Dim firstString As Byte() = _
uniEncoding.GetBytes("Invalid file path characters are: ")
Dim secondString As Byte() = _
uniEncoding.GetBytes(Path.GetInvalidPathChars())
Dim memStream As New MemoryStream(100)
Try
' Write the first string to the stream.
memStream.Write(firstString, 0 , firstString.Length)
' Write the second string to the stream, byte by byte.
count = 0
While(count < secondString.Length)
memStream.WriteByte(secondString(count))
count += 1
End While
' Write the stream properties to the console.
Console.WriteLine( _
"Capacity = {0}, Length = {1}, Position = {2}", _
memStream.Capacity.ToString(), _
memStream.Length.ToString(), _
memStream.Position.ToString())
' Set the stream position to the beginning of the stream.
memStream.Seek(0, SeekOrigin.Begin)
' Read the first 20 bytes from the stream.
byteArray = _
New Byte(CType(memStream.Length, Integer)){}
count = memStream.Read(byteArray, 0, 20)
' Read the remaining Bytes, Byte by Byte.
While(count < memStream.Length)
byteArray(count) = _
Convert.ToByte(memStream.ReadByte())
count += 1
End While
' Decode the Byte array into a Char array
' and write it to the console.
charArray = _
New Char(uniEncoding.GetCharCount( _
byteArray, 0, count)){}
uniEncoding.GetDecoder().GetChars( _
byteArray, 0, count, charArray, 0)
Console.WriteLine(charArray)
Finally
memStream.Close()
End Try
End Sub
End Module
See MemoryStream for more information.

Compression to stream

I'm attempting to compress a file to stream which is sent over wcf and decompressed. However with the following code the I'm get not a valid exe when attempting to execute the decompressed exe. Any decompressed exe is around 211-212 bytes lower that the original.
Sub Main()
Dim strm As Stream = CompressToStream("c:\rje\Launcher.exe")
DecompressToFile(strm)
End Sub
Compression Routine
Private Function CompressToStream(ByVal strFullFilename As String) As Stream
If File.Exists(strFullFilename) Then
Dim uncompressedfile As New MemoryStream(File.ReadAllBytes(strFullFilename))
Dim compressedStream As New MemoryStream
Dim compressionStream As New GZipStream(compressedStream, CompressionMode.Compress)
uncompressedfile.CopyToStream(compressionStream)
compressionStream.Flush()
compressedStream.Position = 0
Return compressedStream
End If
Return Nothing
End Function
Extension method to copy streams as using .net3.5
<System.Runtime.CompilerServices.Extension()> _
Private Sub CopyToStream(ByVal input As Stream, ByRef output As Stream)
Dim Buffer(4096) As Byte
Dim numRead As Integer = input.Read(Buffer, 0, Buffer.Length)
Do While numRead <> 0
output.Write(Buffer, 0, numRead)
numRead = input.Read(Buffer, 0, Buffer.Length)
Loop
End Sub
Finally Decompression
Private Sub DecompressToFile(ByVal strmDownload As Stream)
Dim spath As String = "c:\rje\text.exe"
Using outFile As FileStream = File.Create(spath)
Using Decompress As GZipStream = New GZipStream(strmDownload, CompressionMode.Decompress)
' Copy the compressed file into the decompression stream.
Dim buffer(4096) As Byte
Dim numRead As Integer = Decompress.Read(buffer, 0, buffer.Length)
Do While numRead <> 0
outFile.Write(buffer, 0, numRead)
numRead = Decompress.Read(buffer, 0, buffer.Length)
Loop
End Using
outFile.Close()
End Using
End Sub
If someone could point out where I'm going wrong that would be great.
The error was with CompressToStream, amending as follows functions correctly
Private Function CompressToStream(ByVal strFullFilename As String) As Stream
If File.Exists(strFullFilename) Then
Dim compressedStream As New MemoryStream()
Using uncompressedfile As New MemoryStream(File.ReadAllBytes(strFullFilename))
Using compressionStream As New GZipStream(compressedStream, CompressionMode.Compress, True)
uncompressedfile.CopyToStream(compressionStream)
End Using
End Using
compressedStream.Seek(0, SeekOrigin.Begin)
Return compressedStream
End If
Return Nothing
End Function
I still don't have an answer as to why I shouldn't use File.Exists()?
Here are adapted Compress()/Decompress() methods from the sample in the link I posted in my comment:
Private Function Compress(ByVal strFullFilename As FileInfo) As Stream
' Get the stream of the source file.
Dim fi as New FileInfo(strFullFilename)
Dim result As New MemoryStream()
Using inFile As FileStream = fi.OpenRead()
' Compressing:
' Prevent compressing hidden and already compressed files.
If (File.GetAttributes(fi.FullName) And FileAttributes.Hidden) _
<> FileAttributes.Hidden And fi.Extension <> ".gz" Then
' Create the compressed file.
Using Compress As GZipStream = New GZipStream(result, CompressionMode.Compress)
' Copy the source file into the compression stream.
Dim buffer As Byte() = New Byte(4096) {}
Dim numRead As Integer = inFile.Read(buffer, 0, buffer.Length)
Do While numRead <> 0
Compress.Write(buffer, 0, numRead)
numRead = inFile.Read(buffer, 0, buffer.Length)
Loop
'Console.WriteLine("Compressed {0} from {1} to {2} bytes.", fi.Name, fi.Length.ToString(), result.Length.ToString())
End Using
End If
End Using
Return result
End Sub
' Method to decompress.
Private Sub Decompress(ByVal strmDownload As Stream, ByVal resultFileName As String)
' Create the decompressed file.
Using outFile As FileStream = File.Create(resultFileName)
Using Decomp As GZipStream = New GZipStream(strmDownload, CompressionMode.Decompress)
' Copy the compressed file into the decompression stream.
Dim buffer As Byte() = New Byte(4096) {}
Dim numRead As Integer = Decompress.Read(buffer, 0, buffer.Length)
Do While numRead <> 0
outFile.Write(buffer, 0, numRead)
numRead = Decomp.Read(buffer, 0, buffer.Length)
Loop
'Console.WriteLine("Decompressed: {0}", fi.Name)
End Using
End Using
End Using
End Sub