Nov 21, 2009

Basic Socket Tutorial For .NET

free web hosting
Open Discussion & Free Web Hosting > Computers & Tech > Programming > Programming General > BASIC / Visual Basic (.NET)

Basic Socket Tutorial For .NET

tansqrx
This little tutorial will help anyone jump into the world of sockets in .NET. Under .NET you will use the system.net namespace.

This tutorial simply goes to the Google homepage, retrieves the HTML and displays it in both a raw output and graphical form. This project was written in VB.NET 2003 and can be downloaded below.

Comment/Reply (w/o sign-up)

tansqrx
'Socket Programming Example in VB.NET 2003
'written by tansqrx
'1/11/05
'This is a basic tutorial for connecting to a webpage the easy way in .NET. I have
'also added many comments for one post in particular, as he is a beginner to .NET


'As a general rule you should always put strict and explicit on
'This will save you many headaches down the road especially in large projects
Option Strict On
Option Explicit On

Imports System.IO

'name of the main class, in this case I have renamed it. You can change what class
'runs first by going to Project>Properties>Common Properties>General and selecting
'FrmMain in the Startup Object.
Public Class FrmMain
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents btnRun As System.Windows.Forms.Button
Friend WithEvents txtRaw As System.Windows.Forms.TextBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents AxWebBrowser1 As AxSHDocVw.AxWebBrowser
Friend WithEvents Label2 As System.Windows.Forms.Label
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(FrmMain))
Me.btnRun = New System.Windows.Forms.Button
Me.txtRaw = New System.Windows.Forms.TextBox
Me.Label1 = New System.Windows.Forms.Label
Me.AxWebBrowser1 = New AxSHDocVw.AxWebBrowser
Me.Label2 = New System.Windows.Forms.Label
CType(Me.AxWebBrowser1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'btnRun
'
Me.btnRun.Location = New System.Drawing.Point(24, 16)
Me.btnRun.Name = "btnRun"
Me.btnRun.TabIndex = 0
Me.btnRun.Text = "Run"
'
'txtRaw
'
Me.txtRaw.Location = New System.Drawing.Point(24, 72)
Me.txtRaw.Multiline = True
Me.txtRaw.Name = "txtRaw"
Me.txtRaw.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.txtRaw.Size = New System.Drawing.Size(544, 120)
Me.txtRaw.TabIndex = 1
Me.txtRaw.Text = ""
'
'Label1
'
Me.Label1.Location = New System.Drawing.Point(24, 48)
Me.Label1.Name = "Label1"
Me.Label1.TabIndex = 2
Me.Label1.Text = "Raw Output"
'
'AxWebBrowser1
'
Me.AxWebBrowser1.Enabled = True
Me.AxWebBrowser1.Location = New System.Drawing.Point(24, 224)
Me.AxWebBrowser1.OcxState = CType(resources.GetObject("AxWebBrowser1.OcxState"), System.Windows.Forms.AxHost.State)
Me.AxWebBrowser1.Size = New System.Drawing.Size(544, 128)
Me.AxWebBrowser1.TabIndex = 3
'
'Label2
'
Me.Label2.Location = New System.Drawing.Point(24, 200)
Me.Label2.Name = "Label2"
Me.Label2.TabIndex = 4
Me.Label2.Text = "Web Browser"
'
'FrmMain
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(592, 374)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.AxWebBrowser1)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.txtRaw)
Me.Controls.Add(Me.btnRun)
Me.Name = "FrmMain"
Me.Text = "Form1"
CType(Me.AxWebBrowser1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)

End Sub

#End Region

'This is the place to put items that need to be started when the app loads
Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

'This function runs when you press the Run button on the form
Private Sub btnRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRun.Click
'from here I created a new class: right click on project name in
'solution explorer>Add>Add New Item and name it modSocket.vb

'create an instance of modSocket just like any other variable
'make sure you have new keyword
Dim socket As New modSocket

Dim strLocation As String = "http://google.com"
Dim strResponse As String

'run the request sub,pass the strLocation variable, and get the response
strResponse = socket.request(strLocation)

'write strResponse into the raw output text box
txtRaw.Text = strResponse

'now I want to diplay the requested string graphically. I can use the COM
'object AxWebBrowser which can be added via the designer. This is purely an
'extension of functionality and can be obmitted.
'First the response string must be saved to a local file and then read into
'the AxWebBrowser

'create a FileStream with create attributes
Dim fWriter As New FileStream("temp.html", FileMode.Create)

'create a StreamWriter to help us out
Dim strWriter As New StreamWriter(fWriter)

'Transfer all data from the string into the StreamWriter
Dim iIndex As Integer
For iIndex = 0 To strResponse.Length - 1
strWriter.Write(strResponse.Chars(iIndex))
Next

'make sure everything is out of the stream and then close
strWriter.Flush()
strWriter.Close()

'navigate to the local file. The name is already provied in the FileStream
AxWebBrowser1.Navigate(fWriter.Name.ToString)
'notice that no images are seen, that's because they are retrieved in a
'seperate HTTP request.
End Sub
End Class

 

 

 


Comment/Reply (w/o sign-up)

tansqrx
Option Strict On
Option Explicit On

'this is where you add reference to command classes
Imports System.Net
Imports System.IO
Imports System.Text

Public Class modSocket


Public Function request(ByVal strLocation As String) As String
'create all the variable needed
Dim httpRequest As HttpWebRequest
Dim httpResponse As HttpWebResponse
Dim responseStream As Stream
Dim responseEncoding As Encoding
Dim responseStreamReader As StreamReader
Dim strResponse As String

'for operations that may fail or can throw an exception you should have
'a try/catch
Try
'This is a little gotcha, it seems to me that you should just be
'able to just dim a HttpWebRequest request type but this is how MS
'wanted to do it.
httpRequest = CType(WebRequest.Create(strLocation), HttpWebRequest)
'if for some reason you wanted to set the timeout, in ms
httpRequest.Timeout = 20000

'this is what is passed as the request headers. Not needed but I wanted
'my app to look like it came from IE 6
httpRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"
httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)"

'Create the object to hold the response
httpResponse = CType(httpRequest.GetResponse(), HttpWebResponse)
'The response needs to be converted to a stream
responseStream = httpResponse.GetResponseStream()
'Telling what type of stream encoding
responseEncoding = System.Text.Encoding.GetEncoding("utf-8")
'Now make into a StreamReader for added functionality
responseStreamReader = New StreamReader(responseStream, responseEncoding)

'check to see if anything was returned
If Not responseStreamReader Is Nothing Then
'transfer the data into the StreamReader
strResponse = responseStreamReader.ReadToEnd
End If

'handle possible exceptions
Catch ex As WebException
'this is for the special exception such as a timeout
MessageBox.Show(ex.Status.ToString)
Catch ex As Exception
'any other exceptions
MessageBox.Show(ex.ToString)
End Try
'send the response string back to the main form
Return strResponse
End Function

End Class

Comment/Reply (w/o sign-up)

tansqrx
I could not get the file to upload to the board so it can be found at http://ycc.astahost.com/Files/Sockets_Example.rar

Recompile and then run.

Comment/Reply (w/o sign-up)


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : Socket Net

  1. Help: Multi-threading Trouble In Custom Socket Component - (2)
  2. Help On Inherit A Class In VB.NET ! - Especially System.Net.Sockets.Socket (3)
    I've just move to VB.NET. I need to know how to inherit a class in VB.NET In networking
    application, whenever I want to make a connection, I add the WinSock control to the form and use the
    codes like CODE Privated Sub wSock_Data_Arrival(ByVal bytesTotal as Long) 'Codes go here
    End Sub But in VB.NET, I have to use System.Net.Sockets.socket class. How can I inherit a
    class in VB.NET, handle the events to the object. Please post the code also....



Looking for basic, socket, tutorial, net

See Also,

*SIMILAR VIDEOS*
Searching Video's for basic, socket, tutorial, net
advertisement



Basic Socket Tutorial For .NET

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com