[TUT]Sockets[VBNET]

Posts 1–15 of 25 · Page 1 of 2
[TUT]Sockets[VBNET]
Heya guys!
Today I started to learn socket programing and I found it really interesting.
Now I will show some of you guys something about the sockets. First of all we need to know what are the sockets and how they work.

1: What are sockets?
2: Sockets were development on UNIX for the first time, they are used to send a data between 2 or more machines.

1: How they work?
2: Well, let's take for example 2 phones, 1 is the phone that will call, and the other one is that one that will get the call. In sockets:

1st Phone -- Client Machine
2nd Phone -- Listener Machine

When the call begins and the second phone accept the call the voice will be transfer by packet data. In our case the packet data is the socket. If you want to call the 2nd phone you need the phone number and the prefix. In socket programing the number is the IP of the machine and the prefix is the port.

Code:
<IP>:<Port>
Microsoft Visual Basic has a namespace dedicated to Windows Sockets (WinSock).
Code:
Imports System.Net.Sockets
Now let's start...
Make 2 Console applications (1: Listener, 2: Client).

First we have to create our listener by putting in:
Code:
Dim x As New TcpListener(458) '458 is the current port.
Now the listener is ready... Before creating our socket we need to make sure that our listener is listening by putting the command Start(). ( x.Start() )
Well now the listener is ready, and we need the socket.

Code:
Dim s As Socket = x.AcceptSocket
The data that the socket will transfer is a array of bytes, but we want to send a message (String), so we have to convert the string into a array of bytes.

Code:
        Dim ace As String = "Hello server!"
        If s.Receive(System.Text.ASCIIEncoding.ASCII.GetBytes(ace)) Then
            Dim r As String = "Heya!"
            Console.WriteLine("Got a message from the client! (" & ace & ")")
            s.Send(System.Text.ASCIIEncoding.ASCII.GetBytes(r))
        End If
This will pretty much wait until the client sends the message and then the server will respond with "Heya!".

Server App:
Code:
Imports System.Net.Sockets
Module Module1

    Sub Main()
        Dim x As New TcpListener(458)
        Console.WriteLine("Waiting for the message.....")
        x.Start()
        Dim s As Socket = x.AcceptSocket
        Dim ace As String = "Hello server!"
        If s.Receive(System.Text.ASCIIEncoding.ASCII.GetBytes(ace)) Then
            Dim r As String = "Heya!"
            Console.WriteLine("Got a message from the client! (" & ace & ")")
            s.Send(System.Text.ASCIIEncoding.ASCII.GetBytes(r))
        End If
        Console.ReadKey()
    End Sub

End Module
Now that we have our server we need the client. We are going to work into machines that are connected at the same network, so into the hostname we have to put localhost, and for the port the same port as in the listener.

Code:
Dim x As New TcpClient("localhost", 458)
The client will automatically connect to the server and got the sockets. To read/write the socket(s) we need the function GetStream().

Code:
Dim s As System.IO.Stream = x.GetStream
Well, since we want to send the first socket from the client to the server we need to call the Write() function of the stream.

Code:
        Dim ace As String = "Hello server!"
        *****ndBufferSize = ace.Length
        If x.Connected Then
            s.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(ace), 0, ace.Length)
        End If
After that the stream will write into the socket our message (Hello server!), and the client will directly send the socket to the server.

Remember? At our server code we did put...
Code:
        If s.Receive(System.Text.ASCIIEncoding.ASCII.GetBytes(ace)) Then
            Dim r As String = "Heya!"
            Console.WriteLine("Got a message from the client! (" & ace & ")")
            s.Send(System.Text.ASCIIEncoding.ASCII.GetBytes(r))
        End If
So now that the client did send the socket with the specific value (String), the listener will reply with "Heya!".

So we need to put in our client code...
Code:
        If s.Read(System.Text.ASCIIEncoding.ASCII.GetBytes(str), 0, str.Length) Then
            Console.WriteLine("Server says: " & str)
        End If
Client Code:
Code:
Imports System.Net.Sockets
Module Module1

    Sub Main()
        Dim x As New TcpClient("localhost", 458)
        Dim s As System.IO.Stream = x.GetStream
        Dim ace As String = "Hello server!"
        *****ndBufferSize = ace.Length
        If x.Connected Then
            s.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(ace), 0, ace.Length)
        End If
        Dim str As String = "Heya!"
        If s.Read(System.Text.ASCIIEncoding.ASCII.GetBytes(str), 0, str.Length) Then
            Console.WriteLine("Server says: " & str)
        End If
        Console.ReadKey()
    End Sub

End Module
NOTE: First run the server app, and then the client one....

Now run and test!! =)
The server will say:

Waiting for the message.....
Got a message from the client! (Hello server!)
and the client will write:
Server says: Heya!
Thx for reading and I hope that you did learn something new today! =)
Looks good, however, please do not declare using "x" or "s" or something similiar as name.
Quote Originally Posted by Blubb1337 View Post
Looks good, however, please do not declare using "x" or "s" or something similiar as name.
In every code example you have

Code:
Dim x As String ........
So it's not like you can talk Kev, Although I do agree with the principal of accurate variable naming. 'ace', 'r', 's', are hardly appropriate variable names.

Good tut by the way,
I may do it with strings, but I wouldn't do it with a tcpclient or anything like that lol.
Quote Originally Posted by Blubb1337 View Post
I may do it with strings, but I wouldn't do it with a tcpclient or anything like that lol.
A variable is a variable no matter the type
Buuuut, we're getting a little off the sockets topic here.
Nice Tutorial Ace.

@Kevin: My variable names include;
jjj, xqw, qqq, w2, edf .... etc...

Doesn't really matter. Helps making it hard for the person who decompiles your code :P
Moved to tutorials.

Looks great, Thanks.
Quote Originally Posted by NextGen1 View Post
Moved to tutorials.

Looks great, Thanks.
It's gunna die now

I only found it again because of Subscribed Threads. Can't we just remove this bloody section? Add like a "tutorials" subsection to each programming language section?
Quote Originally Posted by Jason View Post


It's gunna die now

I only found it again because of Subscribed Threads. Can't we just remove this bloody section? Add like a "tutorials" subsection to each programming language section?
100 % agree with ya Jason. I am writing an extensive tutorial on Marshaling, but I don't think I will post it. Simply, because it will die.
@ Hassan & Jason, It's going to die anyway, EVERY tutorial in or out of vb section does.

You guys seem to miss the common sense aspect of it all, the tut section is dead because noone uses it. The mind set "it is going to die now" is what makes it die, if everyone would use the tut section it would stay alive.

So only fault is at the hands of the members, not mine. Tuts go in tut section.

Sorry.

If each section would get a tutorial sub section then yes it would help, but in the meantime, that is where they go.

Yes it's the fault of the members, but it's also partly the fault of the moderators that DIDN'T put tuts in here for like what....6 months?

Now no-one knows about this section at all, no-one goes here...hence, dead section. Sure it might seem common sense but I think I'd look for a VB related tutorial in the VB section first...but hey, maybe I lack common sense. As it stands, putting threads in here just kills them prematurely. Sure, 99% of all threads die within a week, but that doesn't mean you should foreshorten its time, it has useful information that about 0.01% of the VB community will ever see
thx guys =)

out-of-topic:
NextGen is right, the tuts section is dead cause no1 take care of it.....

BTW:
Is this the first tut with sockets? Cause I can't find anyothers
@ Jason, Tuts go in tuts, Like I said, I don't disagree, but that is the reason for the section, if you (as much as I do) want to build sections, then add tutorials to the tut section, take some time and write some, if the are good tuts then the section will build itself, the whole tut section is full of the same leeched injector source and 2 line spammer sources.
Quote Originally Posted by NextGen1 View Post
@ Jason, Tuts go in tuts, Like I said, I don't disagree, but that is the reason for the section, if you (as much as I do) want to build sections, then add tutorials to the tut section, take some time and write some, if the are good tuts then the section will build itself, the whole tut section is full of the same leeched injector source and 2 line spammer sources.
eeeeeeey, mine isn't leeched
Quote Originally Posted by NextGen1 View Post
@ Jason, Tuts go in tuts, Like I said, I don't disagree, but that is the reason for the section, if you (as much as I do) want to build sections, then add tutorials to the tut section, take some time and write some, if the are good tuts then the section will build itself, the whole tut section is full of the same leeched injector source and 2 line spammer sources.
I've written a few tuts now and without fail they go to shit as soon as they get moved here . TBH I'm not actually interested in the slightest about building up this section lol. I'd prefer to have the VB tuts in the VB Section and build that up, personally.
Posts 1–15 of 25 · Page 1 of 2

Post a Reply

Tags for this Thread

None

Need help?