Thursday, September 17, 2009

How to: Create a Socket Listener

http://msdn.microsoft.com/en-us/library/bb397809.aspx#


The .NET Compact Framework supports socket-based network communications. For considerations that are specific to programming sockets in the .NET Compact Framework, see Socket Programming.
This example creates an instance of a server application and an instance of a client application, and demonstrates how the two applications communicate over a socket-based connection. The localhost address is used for the server; therefore, both applications run on the client. An instance of the server must be running before the client can communicate with it.

This is the complete code "How to: Create a Socket Listner"

Server:

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class server
Inherits System.Windows.Forms.Form
Private WithEvents startButton As System.Windows.Forms.Button
Private Shared output As String = ""
Public Sub New()
Me.InitializeComponent()
End Sub
Private Sub InitializeComponent()
Me.startButton = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'startButton
'
Me.startButton.Location = New System.Drawing.Point(37, 36)
Me.startButton.Name = "startButton"
Me.startButton.Size = New System.Drawing.Size(148, 23)
Me.startButton.TabIndex = 0
Me.startButton.Text = "Start Server"
'
'server
'
Me.ClientSize = New System.Drawing.Size(506, 219)
Me.Controls.Add(Me.startButton)
Me.Name = "server"
Me.Text = "Server"
Me.ResumeLayout(False)
End Sub

Private Sub startButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles startButton.Click
' Disable the Start button until
' the asynchronous operation is done.
Me.startButton.Enabled = False
' Start the asynchronous operation.
Me.createListener()
End Sub
Public Sub createListener()
' Create an instance of the TcpListener class.
Dim tcpListener As TcpListener = Nothing
Dim ipAddress As IPAddress = Dns.GetHostEntry("localhost").AddressList(0)
Try
' Set the listener on the local IP address.
' and specify the port.
tcpListener = New TcpListener(ipAddress, 13)
tcpListener.Start()
output = "Waiting for a connection..."
Catch e As Exception
output = "Error: " + e.ToString()
MessageBox.Show(output)
End Try
While True
' Always use a Sleep call in a while(true) loop
' to avoid locking up your CPU.
Thread.Sleep(10)
' Create a TCP socket.
' If you ran this server on the desktop, you could use
' Socket socket = tcpListener.AcceptSocket()
' for greater flexibility.
Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
' Read the data stream from the client.
Dim bytes(255) As Byte
Dim stream As NetworkStream = tcpClient.GetStream()
stream.Read(bytes, 0, bytes.Length)
Dim helper As New SocketHelper()
helper.processMsg(tcpClient, stream, bytes)
End While
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.createListener()
End Sub
End Class
Class SocketHelper
Private mscClient As TcpClient
Private mstrMessage As String
Private mstrResponse As String
Private bytesSent() As Byte
Public Sub processMsg(ByVal client As TcpClient, ByVal stream As NetworkStream, ByVal bytesReceived() As Byte)
' Handle the message received and
' send a response back to the client.
mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length)
mscClient = client
mstrMessage = mstrMessage.Substring(0, 5)
If mstrMessage.Equals("Hello") Then
mstrResponse = "Goodbye"
Else
mstrResponse = "What?"
End If
bytesSent = Encoding.ASCII.GetBytes(mstrResponse)
stream.Write(bytesSent, 0, bytesSent.Length)
End Sub
End Class


Client:

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class client
Inherits System.Windows.Forms.Form
Private WithEvents Button1 As System.Windows.Forms.Button

Public Sub New()
Me.InitializeComponent()
End Sub

Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(37, 36)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(148, 23)
Me.Button1.TabIndex = 0
Me.Button1.Text = "Send to Server"
'
'client
'
Me.ClientSize = New System.Drawing.Size(506, 219)
Me.Controls.Add(Me.Button1)
Me.Name = "client"
Me.Text = "Client"
Me.ResumeLayout(False)
End Sub


Shared Sub Connect(ByVal serverIP As String, ByVal message As String)
Dim output As String = ""
Try
' Create a TcpClient.
' The client requires a TcpServer that is connected
' to the same address specified by the server and port
' combination.
Dim port As Int32 = 13
Dim client As New TcpClient(serverIP, port)
' Translate the passed message into ASCII and store it as a byte array.
Dim data(255) As [Byte]
data = System.Text.Encoding.ASCII.GetBytes(message)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
Dim stream As NetworkStream = client.GetStream()
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
output = "Sent: " + message
MessageBox.Show(output)
' Buffer to store the response bytes.
data = New [Byte](255) {}
' String to store the response ASCII representation.
Dim responseData As String = String.Empty
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
output = "Received: " + responseData
MessageBox.Show(output)
' Close everything.
stream.Close()
client.Close()
Catch e As ArgumentNullException
output = "ArgumentNullException: " + e.ToString()
MessageBox.Show(output)
Catch e As SocketException
output = "SocketException: " + e.ToString()
MessageBox.Show(output)
End Try
End Sub
Shared Sub Main()
Application.Run(New client())
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' In this code example, use a hard-coded
' IP address and message.
Dim serverIP As String = "localhost"
Dim message As String = "Hello"
Connect(serverIP, message)
End Sub
End Class

Tuesday, October 7, 2008

Reference name is greyed out

if the reference name is greyed out, then you need to check the target framework in your advanced compile settings.

Friday, September 26, 2008

Display different colors in RichTextBox


Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

RichTextBox1.SelectionStart = RichTextBox1.Find("are")
'using the Find method to find the text "are" and setting it's return
'property to SelectionStart which selects the text
RichTextBox1.SelectionColor = Color.Blue
'setting the color for the selected text with SelectionColor property
RichTextBox1.SelectionStart = RichTextBox1.Find("working")
RichTextBox1.SelectionColor = Color.Yellow

End Sub

End Class

Best explaination of method overload I have seen

A method is either a subroutine or a function. The difference, of course, is that a function in Visual Basic returns a value, while a subroutine does not. Both functions and subroutines can accept arguments.

When choosing method names, you should, of course, use a name that reflects what the method does. But there are situations where you need methods that do similar things but accept different lists of arguments. For example, you may need a method that prints a double, as well as a method that prints a string. What do you do? You can write two methods and call them PrintDouble and PrintString respectively. But you really want to call both methods Print, because that is what they do.

OOP languages, including VB.NET, allow multiple methods to have the same name, as long as those methods have different lists of arguments. This is called method overloading. Each of the methods with the same name is comfortably called an overload. In VB.NET, you add the keyword Overloads as the first part in the method signature. The use of the Overloads keyword is optional, however; you can still have methods with the same name without using the keyword. For example, consider Listing 14, which shows the class Calculator with two Add methods. The first overload accepts two integers and the second overload accepts two doubles.

Code sample

Imports System

Class Calculator
Overloads Public Function Add(a As Integer, b As Integer) As Integer Add = a + b End Function
Overloads Public Function Add(a As Double, b As Double) As Double Add = a + b End Function
End Class

Module Module1
Public Sub Main()
Dim counter As Calculator
counter = New Calculator()
' pass two integers
Console.WriteLine(counter.Add(1, 5))
' pass two doubles
Console.WriteLine(counter.Add(1.3, 5.9))
End Sub
End Module

' pass two integers
Console.WriteLine(counter.Add(1, 5))

' pass two doubles
Console.WriteLine(counter.Add(1.3, 5.9))

Thursday, September 25, 2008

Weclome to VB.NET Code Stop

Very Simple Concept --- code samples for specific needs

Lets start with using a string split using a chr() value, in this example I am going to use Chr(13).

call this function and you should be all set.

Private Function SplitStringIntoWords() As Integer
Dim strComplete As String = "This is a" + Chr(13) + " test"
Dim strWords() As String


strWords = strComplete.Split(Chr(13))
Dim i As Integer
For i = 0 To UBound(strWords)
MessageBox.Show(strWords(i))
Next
End Function