Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all 27201 articles
Browse latest View live

Login Form to a server

$
0
0
Hi all,

I am trying to create a sort of login form that logs a user into a "cloud" that other users can also log into, however i only want the "cloud" to allow a maximum of two people on at any one time. Thus meaning that if another user tries to connect, they are told that there are no places left.

Is this possible? And how could it be done?

P.S My VB.NET programming is somewhat limited :(

Many Thanks,

G

VS 2015 File Compare and Move - Same File Name with Different File Extensions

$
0
0
I'm looking for VB code that will compare two files in the same folder which have the same file name with different extensions and move the older of the two to a destination folder.
Name:  idw dwf extn.jpg
Views: 12
Size:  42.2 KB
Can anyone help me with this?
Attached Images
 

Ho to add A column at runtime or programmatically for TableLayoutPanel

$
0
0
Dear Experts,


I have created an TableLayoutPanel to add a datagridview.

So far i can only add one column but it must be 2 or depends on the column of my table.

Below is the code that i have so far.

Code:


        Dim con As New SqlConnection(sqlcon)
        Try
            con.Open()
            Dim cmd As SqlCommand = con.CreateCommand
            cmd.CommandText = "select  distinct B.FullName,A.userid from UserDataInputDetails A inner join Users B on A.UserID=B.UserName"
            cmd.CommandType = CommandType.Text
            'cmd.Parameters.AddWithValue("@username", "kai")
            Dim dr As SqlDataReader = cmd.ExecuteReader
            Dim dt As New DataTable
            dt.Load(dr)

            If dt.Rows.Count > 0 Then
                For i As Integer = 0 To dt.Rows.Count - 1
                    Dim panel As New TableLayoutPanel
                    With panel
                        .BorderStyle = BorderStyle.FixedSingle
                        .Dock = DockStyle.Fill
                        .AutoScroll = True
                        .AutoSizeMode = Windows.Forms.AutoSizeMode.GrowAndShrink
                        .ColumnCount =  = dt.Rows.Count
                        .BorderStyle = BorderStyle.FixedSingle
                        .GrowStyle = TableLayoutPanelGrowStyle.AddColumns
                        TabPage1.Controls.Add(panel)
                        Dim dgview As New DataGridView
                        With dgview
                            .AllowUserToOrderColumns = False
                            panel.Controls.Add(dgview)
                            .BorderStyle = BorderStyle.FixedSingle
                            .ColumnCount = 1
                            ApplyGridStyle(dgview, False, False)
                            .Columns(0).HeaderText = dt.Rows(i).Item("FullName").ToString
                            Dim UserID As String = dt.Rows(i).Item("userid").ToString
                            Dim con2 As New SqlConnection(sqlcon)
                            Try
                                con2.Open()
                                Dim cmd2 As SqlCommand = con2.CreateCommand
                                cmd2.CommandText = "select BKGNO from UserDataInputDetails where userid=@userID"
                                cmd2.CommandType = CommandType.Text
                                cmd2.Parameters.AddWithValue("@userID", UserID)
                                Dim dr1 As SqlDataReader = cmd2.ExecuteReader
                                Dim dt1 As New DataTable
                                dt1.Load(dr1)
                                If dt1.Rows.Count > 0 Then
                                    For x As Integer = 0 To dt1.Rows.Count - 1
                                        .Rows.Add(dt1.Rows(x).Item("BKGNO"))
                                    Next
                                End If
                                cmd2.ExecuteNonQuery()
                            Catch ex As Exception
                                MsgBox(ex.Message & vbNewLine & "Error in Loading Booking Number")
                            Finally
                                If con2 IsNot Nothing Then
                                    con2.Close()
                                    con2.Dispose()
                                End If
                            End Try

                            .MultiSelect = True
                            .AllowDrop = True
                            .BackgroundColor = Color.White
                            .Height = 600
                            .Width = 400
                            .Dock = DockStyle.Fill
                        End With
                    End With

                Next
            End If
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.Message & vbNewLine & "Error in Populating User.")
        Finally
            If con IsNot Nothing Then
                con.Close()
                con.Dispose()
            End If
        End Try

Thanks.

How can i edit this

$
0
0
How can i edit Login Logout, or buttons to have a picture on it?

and if someone can, give me some good button design for login cancel? thanks

Decode encoded-as-aaencode JavaScript program

$
0
0
Hi guys. :wave:

I'm trying to implement something like this into my app. I know it's too much to ask but, does anyone alrady has something like this for vb.net?

Code:

http://cat-in-136.github.io/2010/12/aadecode-decode-encoded-as-aaencode.html
I'm basically trying to send encoded text to one RichTextBox and automatically decode it into readable text, any help is appreciated. :)

How to parse this data into a list box?

$
0
0
What would be the best way to parse this data, line by line... to put in into a listbox / data grid?
Quote:

Interface name : Wi-Fi
There are 4 networks currently visible.

SSID 1 : WIFI-SSID2832
Network type : Infrastructure
Authentication : WPA2-Personal
Encryption : CCMP
BSSID 1 : xx:xx:xx:xx:xx:xx
Signal : 10%
Radio type : 802.11n
Channel : 11
Basic rates (Mbps) : 1 2 5.5 11
Other rates (Mbps) : 6 9 12 18 24 36 48 54

SSID 2 : WIFI-SSID5832
Network type : Infrastructure
Authentication : Open
Encryption : None
BSSID 1 : xx:xx:xx:xx:xx:xx
Signal : 8%
Radio type : 802.11n
Channel : 11
Basic rates (Mbps) : 1 2 5.5 11
Other rates (Mbps) : 6 9 12 18 24 36 48 54
BSSID 2 : xx:xx:xx:xx:xx:xx
Signal : 80%
Radio type : 802.11n
Channel : 6
Basic rates (Mbps) : 1 2 5.5 11
Other rates (Mbps) : 6 9 12 18 24 36 48 54
BSSID 3 : xx:xx:xx:xx:xx:xx
Signal : 85%
Radio type : 802.11ac
Channel : 44
Basic rates (Mbps) : 6 12 24
Other rates (Mbps) : 9 18 36 48 54

SSID 3 : BTWifi-X
Network type : Infrastructure
Authentication : WPA2-Enterprise
Encryption : CCMP
BSSID 1 : 52:8a:ae:d4:d1:8c
Signal : 10%
Radio type : 802.11n
Channel : 11
Basic rates (Mbps) : 1 2 5.5 11
Other rates (Mbps) : 6 9 12 18 24 36 48 54
BSSID 2 : xx:xx:xx:xx:xx:xx
Signal : 80%
Radio type : 802.11n
Channel : 6
Basic rates (Mbps) : 1 2 5.5 11
Other rates (Mbps) : 6 9 12 18 24 36 48 54
BSSID 3 : xx:xx:xx:xx:xx:xx
Signal : 85%
Radio type : 802.11ac
Channel : 44
Basic rates (Mbps) : 6 12 24
Other rates (Mbps) : 9 18 36 48 54

SSID 4 : WIFI-SSID4958
Network type : Infrastructure
Authentication : WPA2-Personal
Encryption : CCMP
BSSID 1 : MAC
Signal : 80%
Radio type : 802.11n
Channel : 6
Basic rates (Mbps) : 1 2 5.5 11
Other rates (Mbps) : 6 9 12 18 24 36 48 54

Month Calendar bolded dates color (style)

$
0
0
Hi,
I'm working on an app and I've encountered a problem.
I need to set 2 types of dates in a month calendar.

1 - red (busy days)
2 - green (active days)

It can be done with text color change or draw a rectangle about the date.


I've search the internet and I haven't found a working solution. I hope you can help me.


I count on you ;)

Help With Regex *urgent*

$
0
0
Hi,

I would like to ask for help with regex. Im noob with regex, never understood it, never use it. Basically im trying to replace some text with new line.

I have this text: (it is only 1 line of text together)
Code:

\(5.24)[c4d1.8]We rarely see the Leopards.\(2.24)[c4d2.56]Most of the time, they're on the snowy side of the valley.\(5.43)[c4d2]But we've spotted a few on this side.
Im trying to replace all \(x.xx) with new line except the first one. So it should look like this

Code:

[c4d1.8]We rarely see the Leopards.
[c4d2.56]Most of the time, they're on the snowy side of the valley.
[c4d2]But we've spotted a few on this side.

Anyone can help me out to write snipped code pls ?

Thx

VS 2010 VB 2010 - Month Calendar Control

$
0
0
Is it possible to select a date in a month calendar control and have that date highlighted indicating that it has been selected?

VS 2015 Null Reference exception in treeview

$
0
0
hello everyone,

I am having a hard time trying to select a specific node value and bind it to a source. what I am trying to make the code do is during a mouse click/selection event if the child node "" is selected under this parent node then this child will be bound to this table binding source. so, for each child I click on under that parent it will bring up their binding sources as well. I havent made it to looping yet I am just trying to get 1 source to work properly then onward from there.


Code:

Sub treeView1_NodeMouseClick(ByVal sender As Object, ByVal e As TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseClick
        If e.Node.Text.Equals(TreeView1.SelectedNode.Nodes(0).Nodes("Anderson")) Then
            DataGridView1.DataSource = AndersonBindingSource
        End If

VS 2010 Calculator Arithmetic Operators not working!

$
0
0
I am creating a calculator via Windows Form in Visual Basic Studio 2010.
I have attached my calculator to the forum available for download, if anyone would like to discover what the problem is and what solutions there are.
On a side note, I have designed the calculator and inserted different functions for efficiency.

I am creating this calculator for fun and happened to came across an error.

For example, when I insert 2 numbers 1 + 5 and I press equals "=" the calculator gives back and incorrect number of "0." every time, no matter what numbers you insert.

I would greatly appreciate any assistance with this.

Thanks,

cozmen
Attached Files

VS 2015 the first null ist not shown

$
0
0
dear friends,

i have sql with a datatable and i created a datasource for this sql datatabe. when i insert data into the column, the first zero is not shown in the datagridview. the column is a int datatype and allow dbnull is true. when i put the zero in middle of number it works .

VS 2015 Database one column to ListBox?

$
0
0
Hi,

From my database I have managed to fire a query so select just one column of the name of the details I want.
It shows up fine in the data grid but I want to use ListBox instead of DataGrid.

How can I achieve this?


Here is my code:



This is the result:




Please let me know what I can do.

how to "encrypt" a key

$
0
0
Hi.
I am trying to think of a way to sort of encrypt a key inside a windows app.
I will explain the situation in a web app to give you a clue.
In a web app, everything can be javascript but the log in function. This function is hit when the web app runs and has the log in information in page_load. So everything is on server side and users cannot know the log details. They just receive back a temp key that they can use freely in javascript's web app(as it expires in 10 minutes ), "locked" with their distinctive access criteria (so anyone can "hack" and see it).
So the server function will "hide" the initial log details .
However since a .NET app can be viewed and hacked so easy as drinking water, thus getting the key from form_load, I was wondering how to simulate the web app.
Obviously I cannot store the key in plain text. If i hash the key I am going to checked against a hashed value, so I cannot use the "actually" key (as it is hashed) and produce a temp key,as I need the non encrypted valued to create a temp key. If I MD5 the key then , again I need the intermediate key to decrypt, so I need to hide it also.
If i use an SQL db to get back the key, again I need a connection.
I was thinking of use an app.config and encrypt the value there but I need a stable server so the value can be gotten from there.So, safe but again i must have a user-pass to distinguish who get's back the credentials, so again the user pass will be stored in the application and I must still encrypt those.
So in short, is there a way to encrypt a value in win app without someone can "hack" in and see the credentials, or hash it but be able to get the real value for a log in?
Thanks.

VS 2015 How to reference functions in a class without creating an object.

$
0
0
How could I reference a function in a class without first creating an object of the class?

What I'm currently doing:

Dim MyC as new MyClass
MsgBox(MyC.MyFunction)

What I would like to be able to do:

MsgBox(MyClass.MyFunction)

Basically as if I were Importing the Class.

Thanks.

VS 2013 Validate a file

$
0
0
Hey all,
Our software creates a PDF and a CSV report file of a real world process that we control. The CSV is created by simply dumping all of the process variables and data to a text file. The PDF is made by first creating an image of the report (mostly charts, and some text). Then using iTextSharp, we add the image to a new PDF document and save it. All of this works fine.

I need a way to know if these documents have been modified after we have created them. Knowing the hows, whats, and whens about the modification would be nice, but it is not necessary. We just need to be able to take one of the files, turn a crank and verify it as authentic.

For the CSV files, we create a salted hash of the entire CSV string. We then insert the hash value into the first line of the file. When we need to validate it, we remove the first line, hash the rest and compare the values. This seems to work fine.

I am stuck on the PDF however. I have tried to first create the PDF file, then read it into a byte array, hash the array with salt and then add the hash value back to the file as metadata. To validate it, I remove the metadata, save the temporary PDF, read it into a byte array and hash it. In theory the hash value should be the same, but in theory, $30/bbl oil should equate to $1/gal gas, but it doesn't.

I have code I can show, but first I'd like to ask if there is a better way to know if a file has changed?

So how can one know if a file has been changed?

'Application' is ambiguous between declarations in Modules...

$
0
0
The full error is:
My.Application error BC30562: 'Application' is ambiguous between declarations in Modules 'Videstra.My.MyProject, Videstra.My.MyProject, Videstra.My.MyProject, Videstra.My.MyProject'.

I'm at a loss for where all of these modules are located or what to do about this. The result is that all calls to My.Application.Info.DirectoryPath returns a null string on execution, but shows the above error when debugging.

It seems to be identifying 4 modules with the same name, but I don't know where to look for what look to be duplicate declarations...

The future for VB? Discussion.

$
0
0
If this isn't the right place for a discussion please move the thread.

I've recently tried getting into a bit of game development, something I've never tried before, my history has been automated business systems so my form design, SQL and process skills are pretty good. (Even if I do say so myself) But I thought, why not get to learn some of the other 80% of the language I've never touched. Hence the spurious messages from myself over the last few months.

Sadly, having joined a couple of gaming forums and struggled to find people to help me with VB, I've realised most people learning to code from scratch using VS recently have chosen C#. I'm confused by this, as C# is all {{'s and }}'s while Basic is still very readable, and there are very few foundation reasons to chose either over another. They use the same compiler and the output is identical, so why C#?

Personally I think there is a stigma attached to VB, it was first developed as a dead end solution for designing forms and application flow, it had very limited functionality but people started using it. It's now a different beast altogether and for the above reasons I really don't get why people don't take it up first. Maybe people's ego's are boosted by the verbal link to C.

But, that's not the point of my post.

Microsoft obviously think there is a healthy future for VB, it hasn't had a major re-write since 6, but they've just written the last version (14) from the ground up. You don't put that amount of work into a project if you think it'll be dead in a couple of years, but there are still huge holes, no native iOS or Android support for example.

So, what are your thoughts? What do you think the future is for our much loved language?

VS 2012 Null Reference On Close()

$
0
0
My situation is pretty much as follows:
Code:

Public Class frmFarm1
 Dim strFarmerFirstList As New List(Of String)
 Dim strFarmerLastList As New List(Of String)
  --------
 strFarmerFirstList.Add(InputBox("Please input the FIRST name of your farmer.", "CHARACTER CREATION"))
Close()
        strFarmerLastList.Add(InputBox("Please input the LAST name of your farmer.", "CHARACTER CREATION"))
        GlobalVariable.strFieldFarmer.Add(strFarmerFirstList.Item(strFarmerFirstList.Count - 1) & " " & strFarmerLastList.Item(strFarmerLastList.Count - 1))
end Class

Public Class GlobalVariable
Public Shared strFieldFarmer As New List(Of String)
end Class

My problem is that I can only seem to use Close() after I have put the entire string together into the strFieldFarmer. If I place it as shown above I get a null reference error. Using the End feature is working fine but it makes me feel like I am doing something wrong to have to change my method of closing so dramatically.

My guess was that strFarmerFirstList was the problem however using breakpoints I determined that at the time of the crash it was set to a single element of ""; which in my understanding would not cause that error.

Now I know the above code seems slightly counter-productive because at this time I am not actually checking if the user is clicking Cancel; I am not worried about that right this second; I just want this form to close properly at any stage of loading. Thank you for any help you can offer; I know that this probably a dead simple issue but I am tearing my hair out trying to get this program to close properly.

Extend existing server-client connection with binary data interchange

$
0
0
Hi,

I have an already existing server-client application that works well for my intends. But so far it's only sending / receiving text-data (type string). I am now wondering if it's possible to extend the architecture with a function for sending (and one for receiving I guess) binary data e.g. a file or just a serialized object my program is using. I found some code searching the net but so far have no clue how to integrate. Maybe someone here can help me out.

How it works so far...

VB.NET Code:
  1. Friend clients As New Hashtable()
  2.     Friend listener As TcpListener
  3.     Friend listenerThread As Threading.Thread
  4.     Friend client As TcpClient
  5.     Friend readBuffer(READ_BUFFER_SIZE) As Byte
  6.  
  7.  
  8.  
  9. 'CONNECT AS A SERVER:
  10.             listenerThread = New Threading.Thread(AddressOf DoListen)
  11.             listenerThread.Start()
  12. ...
  13.     Friend Sub DoListen()
  14.         Try
  15.             ' Listen for new connections.
  16.             listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, CInt(sPort))
  17.             listener.Start()
  18.  
  19.             Do While Not shuttingDown
  20.                 ' Create a new user connection using TcpClient returned by
  21.                 ' TcpListener.AcceptTcpClient()
  22.                 Dim client As New UserConnection(listener.AcceptTcpClient)
  23.  
  24.                 ' Create an event handler to allow the UserConnection to communicate
  25.                 ' with the window.
  26.                 AddHandler client.LineReceived, AddressOf OnLineReceived
  27.                 UpdateStatus("New connection: waiting for login")
  28.             Loop 'Until False
  29.         Catch ex As Exception
  30.             UpdateStatus("FEHLER: " & ex.Message)
  31.             Call WriteErrorLog(ex.GetType.ToString & " - " & ex.Message & " (4)")
  32.         Finally
  33.             shuttingDown = False
  34.         End Try
  35.     End Sub
  36.  
  37.  
  38.  
  39. 'CONNECT AS A CLIENT:
  40. ...
  41.         ElseIf m_Connstate.cTyp = cTyp.Client And m_Connstate.cState = cState.NotConnected Then 'ElseIf Button1.Text = "connect" Then
  42.             If GetInternetConnectedState() = False Then MsgBox("Es besteht keine Internet-Verbindung!", MsgBoxStyle.Exclamation, Me.Text)
  43.             Try
  44.                 ' The TcpClient is a subclass of Socket, providing higher level functionality like streaming.
  45.                 client = New System.Net.Sockets.TcpClient(ResolveDNS(sIP), CInt(sPort))
  46.  
  47.                 ' Start an asynchronous read invoking DoRead to avoid lagging the user interface.
  48.                 client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
  49.  
  50.                 ' Make sure the window is showing before popping up connection dialog.
  51.                 Me.Show()
  52.  
  53.                 SendData("CONNECT" & SepChar & sUserName) 'AttemptLogin()
  54.                 m_Connstate.cState = cState.Connected
  55.             Catch Ex As Exception
  56.                 MsgBox("Server not found.", MsgBoxStyle.Exclamation, Me.Text)
  57.                 m_Connstate.cState = cState.NotConnected
  58.             End Try
  59.  
  60.  
  61. ...
  62.     ' This is the event handler for the UserConnection when it receives a full line.
  63.     ' Parse the cammand and parameters and take appropriate action.
  64.     Private Sub OnLineReceived(ByVal sender As UserConnection, ByVal data As String)
  65.         Dim dataArray() As String
  66.  
  67.         ' Message parts are divided by "|"  Break the string into an array accordingly.
  68.         dataArray = data.Split(CChar(SepChar))
  69.  
  70.         ' dataArray(0) is the command.
  71.         Select Case dataArray(0)
  72.             Case "CONNECT"
  73.                 ConnectUser(dataArray(1), sender)
  74.             Case "CHAT"
  75.                 SendChat(dataArray(1), sender)
  76.             Case "DISCONNECT"
  77.                 DisconnectUser(sender)
  78.             Case "REQUESTUSERS"
  79.                 ListUsers(sender)
  80.             Case Else
  81.                 UpdateStatus("unknown msg:" & data)
  82.         End Select
  83.     End Sub
  84.  
  85. ...
  86.  
  87.     ' This is the callback function for TcpClient.GetStream.Begin to get an asynchronous read.
  88.     Private Sub DoRead(ByVal ar As IAsyncResult)
  89.         Dim BytesRead As Integer
  90.         Dim strMessage As String
  91.  
  92.         Try
  93.             ' Finish asynchronous read into readBuffer and return number of bytes read.
  94.             BytesRead = client.GetStream.EndRead(ar)
  95.             If BytesRead < 1 Then
  96.                 ' If no bytes were read server has close. Disable input window.
  97.                 MarkAsDisconnected()
  98.                 Exit Sub
  99.             End If
  100.  
  101.             ' Convert the byte array the message was saved into
  102.             strMessage = System.Text.Encoding.UTF8.GetString(readBuffer, 0, BytesRead)
  103.             'strMessage = DeMaskUnicode(strMessage)
  104.             'MsgBox("Server schickt:  " & strMessage)
  105.             Static Buffer As String
  106.             Dim msgString As String
  107.             msgString = Buffer & strMessage
  108.             Buffer = ""
  109.             Dim sFeld() As String
  110.             sFeld = Split(msgString, Chr(10))
  111.             Dim i As Integer
  112.             For i = sFeld.GetLowerBound(0) To sFeld.GetUpperBound(0)
  113.                 If Len(sFeld(i)) = 0 Then Exit For
  114.                 sFeld(i) = Replace(sFeld(i), Chr(13), vbCrLf)
  115.                 If Strings.Right(sFeld(i), 1) = Chr(10) Then
  116.                     ProcessCommands(Replace(sFeld(i), vbCrLf, ""))
  117.                 Else
  118.                     Buffer = Buffer & sFeld(i)
  119.                 End If
  120.             Next
  121.  
  122.      
  123.             ' Start a new asynchronous read into readBuffer.
  124.             client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf DoRead, Nothing)
  125.         Catch ex As System.IO.IOException
  126.             MarkAsDisconnected()
  127.             Call WriteErrorLog(ex.GetType.ToString & " - " & ex.Message & " (5)")
  128.         Catch ex As Exception
  129.             MsgBox(ex.GetType.ToString & " ---> " & ex.Message)
  130.         End Try
  131.     End Sub
  132.  
  133.  
  134. ...
  135.     ' This subroutine sends a message to all attached clients except the sender.
  136.     Private Sub SendToClients(ByVal strMessage As String, ByVal sender As UserConnection)
  137.         Dim client As UserConnection
  138.         Dim entry As DictionaryEntry
  139.  
  140.         ' All entries in the clients Hashtable are UserConnection so it is possible
  141.         ' to assign it safely.
  142.         For Each entry In clients
  143.             client = CType(entry.Value, UserConnection)
  144.  
  145.             ' Exclude the sender.
  146.             If client.Name <> sender.Name Then
  147.                 client.SendData(strMessage)
  148.             End If
  149.         Next
  150.     End Sub
  151.  
  152.  
  153. ...
  154.     ' Use a StreamWriter to send a message to server.
  155.     Private Sub SendData(ByVal data As String)
  156.         SyncLock client.GetStream
  157.             If m_Connstate.cTyp = cTyp.Server And m_Connstate.cState = cState.Connected And clients.Count > 0 Then
  158.                 Call OnLineReceived(DirectCast(clients(sUserName), UserConnection), Replace(data, vbCrLf, ""))
  159.                 Exit Sub
  160.             End If
  161.             Dim writer As New IO.StreamWriter(client.GetStream)
  162.             writer.WriteLine(data)
  163.             writer.Flush()
  164.         End SyncLock
  165.     End Sub
  166.  
  167.  
  168. ...
  169. ' The UserConnection class encapsulates the functionality of a TcpClient connection
  170. ' with streaming for a single user.
  171. Public Class UserConnection
  172.     Implements IDisposable
  173.  
  174.     Private client As TcpClient
  175.     Private readBuffer(READ_BUFFER_SIZE) As Byte
  176.     Private strName As String
  177.     Const READ_BUFFER_SIZE As Integer = 25500
  178.  
  179.     Private PublicIP As String
  180.  
  181.  
  182.     ' The Name property uniquely identifies the user connection.
  183.     Public Property Name() As String
  184.         Get
  185.             Return strName
  186.         End Get
  187.         Set(ByVal Value As String)
  188.             strName = Value
  189.         End Set
  190.     End Property
  191.  
  192.     Public ReadOnly Property PublicIPAddress() As String
  193.         Get
  194.             If PublicIP = String.Empty Then
  195.                 Try
  196.                     ' Get the clients IP address using Client property            
  197.                     Dim ipend As Net.IPEndPoint = DirectCast(client.Client.RemoteEndPoint, Net.IPEndPoint)
  198.                     If Not ipend Is Nothing Then
  199.                         PublicIP = ipend.Address.ToString & ":" & ipend.Port.ToString
  200.                     End If
  201.                 Catch ex As System.ObjectDisposedException
  202.                     PublicIP = String.Empty
  203.                 Catch ex As SocketException
  204.                     PublicIP = String.Empty
  205.                 End Try
  206.             End If
  207.             Return PublicIP
  208.         End Get
  209.     End Property
  210.  
  211.     Public Sub Dispose() Implements IDisposable.Dispose
  212.         DirectCast(client, IDisposable).Dispose()
  213.     End Sub
  214.  
  215.     ' Overload the New operator to set up a read thread.
  216.     Public Sub New(ByVal client As TcpClient)
  217.         Me.client = client
  218.  
  219.         ' This starts the asynchronous read thread.  The data will be saved into readBuffer.
  220.         Me.client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf StreamReceiver, Nothing)
  221.         'Me.client.GetStream.Read(readBuffer, 0, READ_BUFFER_SIZE) 'Synchron
  222.     End Sub
  223.  
  224.     Public Event LineReceived(ByVal sender As UserConnection, ByVal Data As String)
  225.  
  226.     ' This subroutine uses a StreamWriter to send a message to the user.
  227.     Public Sub SendData(ByVal Data As String)
  228.         ' Synclock ensure that no other threads try to use the stream at the same time.
  229.         'MsgBox(Data)
  230.         'Threading.Thread.Sleep(10)
  231.         SyncLock client.GetStream
  232.             Dim writer As New IO.StreamWriter(client.GetStream)
  233.             writer.WriteLine(Data)
  234.  
  235.             ' Make sure all data is sent now.
  236.             writer.Flush()
  237.         End SyncLock
  238.     End Sub
  239.  
  240.     ' This is the callback function for TcpClient.GetStream.Begin. It begins an
  241.     ' asynchronous read from a stream.
  242.     Private Sub StreamReceiver(ByVal ar As IAsyncResult)
  243.         Dim BytesRead As Integer
  244.         Static strMessage As String
  245.  
  246.         Try
  247.             ' Ensure that no other threads try to use the stream at the same time.
  248.             SyncLock client.GetStream
  249.                 ' Finish asynchronous read into readBuffer and get number of bytes read.
  250.                 BytesRead = client.GetStream.EndRead(ar)
  251.             End SyncLock
  252.  
  253.             ' Convert the byte array the message was saved into
  254.             strMessage = Encoding.UTF8.GetString(readBuffer, 0, BytesRead)
  255.  
  256.             'MsgBox("Client schickt  " & strMessage)
  257.             Static Buffer As String
  258.             Dim msgString As String
  259.             msgString = Buffer & strMessage
  260.             Buffer = ""
  261.             Dim sFeld() As String
  262.             sFeld = Split(msgString, Chr(10))
  263.             Dim i As Integer
  264.             For i = sFeld.GetLowerBound(0) To sFeld.GetUpperBound(0)
  265.                 If Len(sFeld(i)) = 0 Then Exit For
  266.                 sFeld(i) = Replace(sFeld(i), Chr(13), vbCrLf)
  267.                 If Strings.Right(sFeld(i), 1) = Chr(10) Then
  268.                     RaiseEvent LineReceived(Me, Strings.Left(sFeld(i), Len(sFeld(i)) - 2))
  269.                 Else
  270.                     Buffer = Buffer & sFeld(i)
  271.                 End If
  272.             Next
  273.  
  274.  
  275.            ' Ensure that no other threads try to use the stream at the same time.
  276.             SyncLock client.GetStream
  277.                 ' Start a new asynchronous read into readBuffer.
  278.                 client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf StreamReceiver, Nothing)
  279.             End SyncLock
  280.         Catch ex As Exception
  281.             Call WriteErrorLog(ex.GetType.ToString & " - " & ex.Message & " (9)")
  282.         End Try
  283.     End Sub
  284. End Class

Can you help me how to implement the possibility of sending / receiving binary formatted data with my existing program structure?

Any hints appreciated!
Thx,
Andreas
Viewing all 27201 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>