Socket abilities - vb.net

I am making a board game for some users. I am learning how to send and receive messages from a socket server.
Private Sub doChat()
Dim requestCount As Integer
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim sendBytes As [Byte]()
Dim serverResponse As String
Dim rCount As String
requestCount = 0
While (True)
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, bytesFrom.Length)
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
msg("From client-" + clNo + dataFromClient)
rCount = Convert.ToString(requestCount)
serverResponse = "Server to clinet(" + clNo + ") " + dataFromClient
sendBytes = Encoding.ASCII.GetBytes(serverResponse)
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Flush()
msg(serverResponse)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub
My question is, what else can I send or receive by sockets? Can I send events? Functions? Elements? Structures? What is the method? I didn't find any article or video clip about this.

Related

TCP Socket doesn't send all the data

I'm trying to send about 250KBytes but I get cut at 8KBytes
I doesn't need any answer from the remote server.
I don't understand what I'm doing wrong.
Is like the tx doesn't change the outbuffer size.
Private Function SendReport7B(ByVal Msg As String, ByVal Host As String, ByVal Port As String) As String
Try
Dim Msgs() As String
Dim Tx As New TcpClient()
Dim stream As NetworkStream = Nothing
Dim LingerMode As New LingerOption(True, 1)
'Dim BSize As Integer
Tx.NoDelay = True
Tx.LingerState = LingerMode
Tx.SendTimeout = 5000
If Msg.Length > Tx.SendBufferSize Then
Tx.SendBufferSize = Msg.Length + 256
End If
Tx.Connect(Host, Port)
Msgs = Msg.Split(Chr(10))
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(Msg)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
stream = Tx.GetStream()
'stream.WriteTimeout = 100
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
Tx.Close()
Return "OK" 'responseData
Catch ex As Exception
Return "Error: " & ex.Message
End Try
End Function

how to Sending SMS through VB.NET

I tried to send sms
it was using textlocal.in
this is the code i tried
Public Function SendSms(sender As Object, e As EventArgs) Handles Button1.Click
Dim apikey = txtAPI.Text
Dim message = txtMsg.Text
Dim numbers = txtNum.Text
Dim strPOST As String
Dim senderName = txtSend.Text
Dim url As String = "https://api.textlocal.in/send/?"
strPOST = url + "apikey=" + apikey _
+ "&numbers=" + numbers _
+ "&message=" + WebUtility.UrlEncode(message) _
+ "&sender=" + sender
Dim request As WebRequest = WebRequest.Create(strPOST)
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(strPOST)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer)
Console.ReadLine()
reader.Close()
dataStream.Close()
response.Close()
If responseFromServer.Length > 0 Then
Return responseFromServer
Else
Return CType(response, HttpWebResponse).StatusDescription
End If
End Function
it is saying Operator '+' is not defined for string "https://api.textlocal.in/send/?a" and type 'Button
In this code sender is the Button that raises the event:
Public Function SendSms(sender As Object
^^^^^^
It is not the phone number of the person sending the message. Replace sender with senderName on this line:
strPOST = url + "apikey=" + apikey _
+ "&numbers=" + numbers _
+ "&message=" + WebUtility.UrlEncode(message) _
+ "&sender=" + sender
^^^^^^^
Do not use + to concatenate strings in vb unless you know exactly what it is doing
Use & to concatenate strings, but in this case I would recommend you use string formatting

when client is closed server crash

I have a problem when I connect to the server from the client, it connects without any issues, but when I close the client window, the server shows the following error message:
The length can not be less than zero. Parameter name: length
And then when I try to reconnect the client it crashes too
This is the server source code:
serverSocket.Start()
AddInfo("Server Started", ConsoleColor.Cyan)
AddInfo("---------------- ACCOUNTS ----------------", ConsoleColor.Blue)
Dim AN As Integer = 0
For Each f In Directory.GetFiles("saved\accounts\")
Dim acc As String = Path.GetFileNameWithoutExtension(f).Split(CChar("%"))(0)
Dim pass As String = Path.GetFileNameWithoutExtension(f).Split(CChar("%"))(1)
AddInfo(acc & " - " & pass, ConsoleColor.Magenta)
AN += 1
Next
AddInfo(AN & " Accounts exists .", ConsoleColor.DarkCyan)
AddInfo("-----------------------------------------------", ConsoleColor.Blue)
clientSocket = serverSocket.AcceptTcpClient()
AddInfo("New Client Connected", ConsoleColor.Yellow)
clients_number += 1
AddInfo("Clients Num : " & clients_number, ConsoleColor.DarkYellow)
requestCount = 0
While (True)
'RECEIVING
requestCount = requestCount + 1
serverStream = clientSocket.GetStream()
Dim bytesFrom(10024) As Byte
serverStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
AddInfo("Data from client - " + dataFromClient, ConsoleColor.DarkYellow)
'### CHEKING ACCOUNT ###
For Each f In Directory.GetFiles("saved\accounts\")
If dataFromClient = Path.GetFileNameWithoutExtension(f) Then
account_avaible = True
End If
Next
If account_avaible = True Then
Dim serverResponse As String = ""
Dim l As New List(Of String)
l.AddRange(File.ReadAllLines("saved\accounts\" & dataFromClient & ".inf"))
For i = 0 To l.Count - 1
serverResponse += l.Item(i).ToString.Split(CChar("="))(1) & "|"
Next
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
serverStream.Write(sendBytes, 0, sendBytes.Length)
serverStream.Flush()
AddInfo(serverResponse, ConsoleColor.Green)
Else
Dim serverResponse As String = "connection_false"
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
serverStream.Write(sendBytes, 0, sendBytes.Length)
serverStream.Flush()
AddInfo(serverResponse, ConsoleColor.Green)
account_avaible = False
End If
End While
I've fixed this problem . thanks #WDS .
i deleted the loop and i made a return to the clientSocket = serverSocket.AcceptTcpClient()
this is the source :
`serverSocket.Start() : AddInfo("Server Started", ConsoleColor.Cyan)
AddInfo("---------------- ACCOUNTS ----------------", ConsoleColor.Blue)
Dim AN As Integer = 0
For Each f In Directory.GetFiles("saved\accounts\")
Dim acc As String = Path.GetFileNameWithoutExtension(f).Split(CChar("%"))(0)
Dim pass As String = Path.GetFileNameWithoutExtension(f).Split(CChar("%"))(1)
AddInfo(acc & " - " & pass, ConsoleColor.Magenta)
AN += 1
Next
AddInfo(AN & " Accounts exists .", ConsoleColor.DarkCyan)
AddInfo("-----------------------------------------------", ConsoleColor.Blue)
Dodo:
account_avaible = False
clientSocket = serverSocket.AcceptTcpClient()
AddInfo("New Client Connected", ConsoleColor.Yellow)
clients_number += 1
AddInfo("Clients Num : " & clients_number, ConsoleColor.DarkYellow)
requestCount = 0
'RECEIVING
requestCount = requestCount + 1
serverStream = clientSocket.GetStream()
Dim bytesFrom(10024) As Byte
serverStream.Read(bytesFrom, 0, clientSocket.ReceiveBufferSize)
Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
AddInfo("Data from client - " + dataFromClient, ConsoleColor.DarkYellow)
'### CHEKING ACCOUNT ###
For Each f In Directory.GetFiles("saved\accounts\")
If dataFromClient = Path.GetFileNameWithoutExtension(f) Then
account_avaible = True
End If
Next
If account_avaible = True Then
Dim serverResponse As String = ""
Dim l As New List(Of String)
l.AddRange(File.ReadAllLines("saved\accounts\" & dataFromClient & ".inf"))
For i = 0 To l.Count - 1
serverResponse += l.Item(i).ToString.Split(CChar("="))(1) & "|"
Next
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
serverStream.Write(sendBytes, 0, sendBytes.Length)
serverStream.Flush()
AddInfo(serverResponse, ConsoleColor.Green)
Else
Dim serverResponse As String = "connection_false"
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
serverStream.Write(sendBytes, 0, sendBytes.Length)
serverStream.Flush()
AddInfo(serverResponse, ConsoleColor.Green)
account_avaible = False
End If
GoTo Dodo
'clientSocket.Close()
'serverSocket.Stop()`
But now i have new problem =/ when i enter an incorrect account msg show ("Incorrect account") and then when i try to enter an other account the client bugg (freeze)

VB.NET FTP Downloaded file corrupt

I want to download all file that located on FTP site. I break into 2 operations. First is to get the list of all files in the directory. Then I proceed to second which download each file. But unfortunately, the downloaded file is corrupt. Worst over, it affect the file on FTP folder. Both folder contains corrupt file. From a viewing thumbnails image to default image thumbnails. How this happen and to overcome this? Below are my code; full code class. I provide as reference and guide to do a correct way :)
Private strTargetPath As String
Private strDestPath As String
Private Sub frmLoader_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
objSQL = New clsSQL
If objSQL.SQLGetAllData Then 'Get data from SQL and insert into an arraylist
strTargetPath = "ftp://192.168.1.120/image/"
strDestPath = "D:\Application\FTPImg\"
ListFileFromFTP()
End If
Catch ex As Exception
strErrMsg = "Oops! Something is wrong with loading login form."
MessageBox.Show(strErrMsg & vbCrLf & "ExMsg: " & ex.Message, "Error message!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub ListFileFromFTP()
Dim arrFile As ArrayList
Dim strPath As String
Try
Dim reqFTP As FtpWebRequest
reqFTP = FtpWebRequest.Create(New Uri(strTargetPath))
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential("user", "user123")
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory
reqFTP.Proxy = Nothing
reqFTP.KeepAlive = False
reqFTP.UsePassive = False
Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
Dim sr As StreamReader
sr = New StreamReader(reqFTP.GetResponse().GetResponseStream())
Dim FileListing As String = sr.ReadLine
arrFile = New ArrayList
While FileListing <> Nothing
strPath = strTargetPath & FileListing
arrFile.Add(strPath)
FileListing = sr.ReadLine
End While
sr.Close()
sr = Nothing
reqFTP = Nothing
response.Close()
For i = 0 To (arrFile.Count - 1)
DownloadImage(arrFile.Item(i))
Next
Catch ex As Exception
strErrMsg = "Oops! Something is wrong with ListFileFromFTP."
MessageBox.Show(strErrMsg & vbCrLf & "ExMsg: " & ex.Message, "Error message!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Function DownloadImage(ByVal strName As String) As String
Dim ftp_request As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Dim strOldName As String
Dim strNewName As String
Dim withoutextension As String
Dim extension As String
Try
strOldName = strTargetPath & strName
withoutextension = Path.GetFileNameWithoutExtension(strOldName)
extension = Path.GetExtension(strOldName)
strNewName = strDestPath & withoutextension & extension
ftp_request = CType(System.Net.FtpWebRequest.Create(strName), System.Net.FtpWebRequest)
ftp_request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
ftp_request.Credentials = New System.Net.NetworkCredential("user", "user123")
ftp_request.UseBinary = True
ftp_request.KeepAlive = False
ftp_request.Proxy = Nothing
Dim response As FtpWebResponse = DirectCast(ftp_request.GetResponse(), FtpWebResponse)
Dim responseStream As IO.Stream = response.GetResponseStream
Dim fs As New IO.FileStream(strNewName, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
responseStream.Close()
response.Close()
Catch ex As WebException
Dim response As FtpWebResponse = ex.Response
If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
MsgBox(response.StatusDescription)
Return String.Empty
Else
MsgBox(response.StatusDescription)
End If
End Try
End Function
For download file, this is the right code that succeed:
Private Sub Download(ByVal strFTPPath As String)
Dim reqFTP As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Try
Dim outputStream As New FileStream(strDestPath & strImgName, FileMode.Create)
reqFTP = DirectCast(FtpWebRequest.Create(New Uri(strFTPPath)), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential("user", "user123")
Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
ftpStream = response.GetResponseStream()
Dim cl As Long = response.ContentLength
Dim bufferSize As Integer = 2048
Dim readCount As Integer
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
readCount = ftpStream.Read(buffer, 0, bufferSize)
While readCount > 0
outputStream.Write(buffer, 0, readCount)
readCount = ftpStream.Read(buffer, 0, bufferSize)
End While
ftpStream.Close()
outputStream.Close()
response.Close()
Catch ex As Exception
If ftpStream IsNot Nothing Then
ftpStream.Close()
ftpStream.Dispose()
End If
Throw New Exception(ex.Message.ToString())
End Try
End Sub
There is something strange in your code. You are closing the responseStream twice.
And you are using ftp request method uploadFile. But then downloading it.
Instead of using the ftp stuff use this instead. Its much more simple and your outsourcing the buffers and streams to microsoft, which should be less buggy than us.
Dim webClient = new WebClient()
webClient.Credentials = new NetworkCredential("user", "user123")
dim response = webClient.UploadFile("ftp://MyFtpAddress","c:\myfile.jpg")
dim sResponse = System.Text.Encoding.Default.GetString(response)

FTP upload ProgressBar in VB.NET

I'm coding an application that uploads a file to a remote FTP server. This is my code that already works.
clsrequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim bFile() As Byte = System.IO.File.ReadAllBytes(rutaorigen)
Dim clsStream As System.IO.Stream = clsrequest.GetRequestStream()
clsStream.Write(bFile, 0, bFile.Length)
clsStream.Close()
clsStream.Dispose()
Now I want to show the progress in a ProgressBar in VB.NET.
Files are not too big (10 MB max).
I've already tried an example that I found here, but it didn't work.
I hope you can help me. Thanks!
Simple progress on console:
Dim request As WebRequest = WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.UploadFile
Using fileStream As Stream = File.OpenRead("C:\local\path\file.zip"),
ftpStream As Stream = request.GetRequestStream()
Dim buffer As Byte() = New Byte(10240 - 1) {}
Dim read As Integer
Do
read = fileStream.Read(buffer, 0, buffer.Length)
If read > 0 Then
ftpStream.Write(buffer, 0, read)
Console.WriteLine("Uploaded {0} bytes", fileStream.Position)
End If
Loop While read > 0
End Using
WinForms GUI progress:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Run Upload on background thread
Task.Run((Sub() Upload()))
End Sub
Sub Upload()
Dim request As WebRequest =
WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.UploadFile
Using fileStream As Stream = File.OpenRead("C:\local\path\file.zip"),
ftpStream As Stream = request.GetRequestStream()
ProgressBar1.Invoke(Sub() ProgressBar1.Maximum = fileStream.Length)
Dim buffer As Byte() = New Byte(10240 - 1) {}
Dim read As Integer
Do
read = fileStream.Read(buffer, 0, buffer.Length)
If read > 0 Then
ftpStream.Write(buffer, 0, read)
ProgressBar1.Invoke(Sub() ProgressBar1.Value = fileStream.Position)
End If
Loop While read > 0
End Using
End Sub
I got this from an example a long time ago. The code should be fairly easy to change for your needs.
Dim clsRequest As System.Net.FtpWebRequest = _
DirectCast(System.Net.WebRequest.Create(ServLabel.Text & TextBox1.Text), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential(PassLabel.Text, UserLabel.Text)
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
rfshTMR.Enabled = True
Dim File() As Byte = System.IO.File.ReadAllBytes(txtFile.Text)
Dim clsStream As System.IO.Stream = _
clsRequest.GetRequestStream()
clsStream.Write(File, 0, File.Length)
For offset As Integer = 0 To File.Length Step 1024
ToolStripProgressBar1.Value = CType(offset * ToolStripProgressBar1.Maximum / File.Length, Integer)
Dim chunkSize As Integer = File.Length - offset - 1
If chunkSize > 1024 Then chunkSize = 1024
clsStream.Write(File, offset, chunkSize)
ToolStripProgressBar1.Value = ToolStripProgressBar1.Maximum
Next
clsStream.Close()
clsStream.Dispose()
MsgBox("File Is Now In Database", MsgBoxStyle.OkOnly, "Upload Complete")