Jump to content
xisto Community
Sign in to follow this  
tansqrx

Basic Socket Tutorial For .NET

Recommended Posts

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.

Share this post


Link to post
Share on other sites

'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 projectsOption Strict OnOption 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 = "https://www.google.de/?gfe_rd=cr&ei=7AkjVIatDsKH8QfNkoC4DQ&gws_rd=ssl; 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 SubEnd Class

Share this post


Link to post
Share on other sites

Option Strict OnOption Explicit On 'this is where you add reference to command classesImports System.NetImports System.IOImports System.TextPublic 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 FunctionEnd Class

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.