Results 1 to 8 of 8

Thread: Need help on converting apps program

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2004
    Posts
    610

    Need help on converting apps program

    hey guyz,
    i got this bunch of codes from msdn.. but its written for console applications...
    how do you convert it so that it will run on a form?
    its abit the long.. thx for your help

    these are the codes

    VB Code:
    1. Imports System
    2. Imports System.Net
    3. Imports System.Net.Sockets
    4. Imports System.Text
    5. Imports System.Threading
    6.  
    7.  
    8. ' State object for reading client data asynchronously
    9. Public Class StateObject
    10.     ' Client  socket.
    11.     Public workSocket As Socket = Nothing
    12.     ' Size of receive buffer.
    13.     Public Const BufferSize As Integer = 1024
    14.     ' Receive buffer.
    15.     Public buffer(BufferSize) As Byte
    16.     ' Received data string.
    17.     Public sb As New StringBuilder
    18. End Class 'StateObject
    19.  
    20. Public Class AsynchronousSocketListener
    21.  
    22.     ' Incoming data from the client.
    23.     Public Shared data As String = Nothing
    24.  
    25.     ' Thread signal.
    26.     Public Shared allDone As New ManualResetEvent(False)
    27.  
    28.  
    29.     Public Sub New()
    30.     End Sub 'New
    31.  
    32.  
    33.     Public Shared Sub StartListening()
    34.         ' Data buffer for incoming data.
    35.         Dim bytes() As Byte = New [Byte](1024) {}
    36.  
    37.         ' Establish the local endpoint for the socket.
    38.         ' The DNS name of the computer
    39.         ' running the listener is "host.contoso.com".
    40.         Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
    41.         Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
    42.         Dim localEndPoint As New IPEndPoint(ipAddress, 11000)
    43.  
    44.         ' Intializes a TCP/IP socket.
    45.         Dim listener As New Socket(AddressFamily.InterNetwork, _
    46.             SocketType.Stream, ProtocolType.Tcp)
    47.  
    48.         ' Bind the socket to the local endpoint and listen for incoming
    49.         ' connections.
    50.         Try
    51.             listener.Bind(localEndPoint)
    52.             listener.Listen(100)
    53.  
    54.             While True
    55.                 ' Set the event to nonsignaled state.
    56.                 allDone.Reset()
    57.  
    58.                 ' Start an asynchronous socket to listen for connections.
    59.                 Console.WriteLine("Waiting for a connection...")
    60.                 listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), _
    61.                 listener)
    62.  
    63.                 ' Wait until a connection is made before continuing.
    64.                 allDone.WaitOne()
    65.             End While
    66.  
    67.         Catch e As Exception
    68.             Console.WriteLine(e.ToString())
    69.         End Try
    70.  
    71.         Console.WriteLine(ControlChars.Cr + "Press ENTER to continue...")
    72.         Console.Read()
    73.     End Sub 'StartListening
    74.  
    75.  
    76.     Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
    77.         ' Signal the main thread to continue.
    78.         allDone.Set()
    79.  
    80.         ' Get the socket that handles the client request.
    81.         Dim listener As Socket = CType(ar.AsyncState, Socket)
    82.         Dim handler As Socket = listener.EndAccept(ar)
    83.  
    84.         ' Create the state object.
    85.         Dim state As New StateObject
    86.         state.workSocket = handler
    87.         handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, _
    88.             New AsyncCallback(AddressOf ReadCallback), state)
    89.     End Sub 'AcceptCallback
    90.  
    91.  
    92.     Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
    93.         Dim content As [String] = [String].Empty
    94.  
    95.         ' Retrieve the state object and the handler socket
    96.         ' from the asynchronous state object.
    97.         Dim state As StateObject = CType(ar.AsyncState, StateObject)
    98.         Dim handler As Socket = state.workSocket
    99.  
    100.         ' Read data from client socket.
    101.         Dim bytesRead As Integer = handler.EndReceive(ar)
    102.  
    103.         If bytesRead > 0 Then
    104.             ' There might be more data, so store the data received so far.
    105.             state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, _
    106.                 bytesRead))
    107.  
    108.             ' Check for end-of-file tag. If it is not there, read
    109.             ' more data.
    110.             content = state.sb.ToString()
    111.             If content.IndexOf("<EOF>") > -1 Then
    112.                 ' All the data has been read from the
    113.                 ' client. Display it on the console.
    114.                 Console.WriteLine("Read {0} bytes from socket. " + _
    115.                     ControlChars.Cr + " Data : {1}", content.Length, content)
    116.                 ' Echo the data back to the client.
    117.                 Send(handler, content)
    118.             Else
    119.                 ' Not all data received. Get more.
    120.                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, _
    121.                     0, New AsyncCallback(AddressOf ReadCallback), state)
    122.             End If
    123.         End If
    124.     End Sub 'ReadCallback
    125.  
    126.  
    127.     Private Shared Sub Send(ByVal handler As Socket, ByVal data As [String])
    128.         ' Convert the string data to byte data using ASCII encoding.
    129.         Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
    130.  
    131.         ' Begin sending the data to the remote device.
    132.         handler.BeginSend(byteData, 0, byteData.Length, 0, _
    133.             New AsyncCallback(AddressOf SendCallback), handler)
    134.     End Sub 'Send
    135.  
    136.  
    137.     Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
    138.         Try
    139.             ' Retrieve the socket from the state object.
    140.             Dim handler As Socket = CType(ar.AsyncState, Socket)
    141.  
    142.             ' Complete sending the data to the remote device.
    143.             Dim bytesSent As Integer = handler.EndSend(ar)
    144.             Console.WriteLine("Sent {0} bytes to client.", bytesSent)
    145.  
    146.             handler.Shutdown(SocketShutdown.Both)
    147.             handler.Close()
    148.  
    149.         Catch e As Exception
    150.             Console.WriteLine(e.ToString())
    151.         End Try
    152.     End Sub 'SendCallback
    153.  
    154.     'Entry point that delegates to C-style main Private Function.
    155.     Public Overloads Shared Sub Main()
    156.         System.Environment.ExitCode = _
    157.         Main(System.Environment.GetCommandLineArgs())
    158.     End Sub
    159.  
    160.     Public Overloads Shared Function Main(ByVal args() As [String]) As Integer
    161.         StartListening()
    162.         Return 0
    163.     End Function 'Main
    164. End Class 'AsynchronousSocketListener

  2. #2

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2004
    Posts
    610

    Re: Need help on converting apps program

    hey ppl.. can anyone help?

  3. #3
    Frenzied Member <ABX's Avatar
    Join Date
    Jul 2002
    Location
    Canada eh...
    Posts
    1,622

    Re: Need help on converting apps program

    Add A New Class to your Project (Project > Add Class...) Name It "AsynchronousSocketListener"

    Now replace all the contents of that new file with this:

    VB Code:
    1. Imports System
    2. Imports System.Net
    3. Imports System.Net.Sockets
    4. Imports System.Text
    5. Imports System.Threading
    6.  
    7.  
    8. ' State object for reading client data asynchronously
    9. Public Class StateObject
    10.     ' Client  socket.
    11.     Public workSocket As Socket = Nothing
    12.     ' Size of receive buffer.
    13.     Public Const BufferSize As Integer = 1024
    14.     ' Receive buffer.
    15.     Public buffer(BufferSize) As Byte
    16.     ' Received data string.
    17.     Public sb As New StringBuilder
    18. End Class 'StateObject
    19.  
    20. Public Class AsynchronousSocketListener
    21.  
    22.     'Added an event...
    23.     Public Shared Event Status(ByVal Info As String)
    24.  
    25.     ' Incoming data from the client.
    26.     Public Shared data As String = Nothing
    27.  
    28.     ' Thread signal.
    29.     Public Shared allDone As New ManualResetEvent(False)
    30.  
    31.  
    32.     Public Sub New()
    33.     End Sub 'New
    34.  
    35.  
    36.     Public Shared Sub StartListening()
    37.         ' Data buffer for incoming data.
    38.         Dim bytes() As Byte = New [Byte](1024) {}
    39.  
    40.         ' Establish the local endpoint for the socket.
    41.         ' The DNS name of the computer
    42.         ' running the listener is "host.contoso.com".
    43.         Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
    44.         Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
    45.         Dim localEndPoint As New IPEndPoint(ipAddress, 11000)
    46.  
    47.         ' Intializes a TCP/IP socket.
    48.         Dim listener As New Socket(AddressFamily.InterNetwork, _
    49.             SocketType.Stream, ProtocolType.Tcp)
    50.  
    51.         ' Bind the socket to the local endpoint and listen for incoming
    52.         ' connections.
    53.         Try
    54.             listener.Bind(localEndPoint)
    55.             listener.Listen(100)
    56.  
    57.             While True
    58.                 ' Set the event to nonsignaled state.
    59.                 allDone.Reset()
    60.  
    61.                 ' Start an asynchronous socket to listen for connections.
    62.                 RaiseEvent Status("Waiting for a connection...")
    63.                 listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), _
    64.                 listener)
    65.  
    66.                 ' Wait until a connection is made before continuing.
    67.                 allDone.WaitOne()
    68.             End While
    69.  
    70.         Catch e As Exception
    71.             RaiseEvent Status(e.ToString())
    72.         End Try
    73.  
    74.         MsgBox("Click OK to continue...")
    75.     End Sub 'StartListening
    76.  
    77.  
    78.     Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
    79.         ' Signal the main thread to continue.
    80.         allDone.Set()
    81.  
    82.         ' Get the socket that handles the client request.
    83.         Dim listener As Socket = CType(ar.AsyncState, Socket)
    84.         Dim handler As Socket = listener.EndAccept(ar)
    85.  
    86.         ' Create the state object.
    87.         Dim state As New StateObject
    88.         state.workSocket = handler
    89.         handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, _
    90.             New AsyncCallback(AddressOf ReadCallback), state)
    91.     End Sub 'AcceptCallback
    92.  
    93.  
    94.     Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
    95.         Dim content As [String] = [String].Empty
    96.  
    97.         ' Retrieve the state object and the handler socket
    98.         ' from the asynchronous state object.
    99.         Dim state As StateObject = CType(ar.AsyncState, StateObject)
    100.         Dim handler As Socket = state.workSocket
    101.  
    102.         ' Read data from client socket.
    103.         Dim bytesRead As Integer = handler.EndReceive(ar)
    104.  
    105.         If bytesRead > 0 Then
    106.             ' There might be more data, so store the data received so far.
    107.             state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, _
    108.                 bytesRead))
    109.  
    110.             ' Check for end-of-file tag. If it is not there, read
    111.             ' more data.
    112.             content = state.sb.ToString()
    113.             If content.IndexOf("<EOF>") > -1 Then
    114.                 ' All the data has been read from the
    115.                 ' client. Display it on the console.
    116.                 RaiseEvent Status(String.Format("Read {0} bytes from socket. " + _
    117.                     ControlChars.Cr + " Data : {1}", content.Length, content))
    118.                 ' Echo the data back to the client.
    119.                 Send(handler, content)
    120.             Else
    121.                 ' Not all data received. Get more.
    122.                 handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, _
    123.                     0, New AsyncCallback(AddressOf ReadCallback), state)
    124.             End If
    125.         End If
    126.     End Sub 'ReadCallback
    127.  
    128.  
    129.     Private Shared Sub Send(ByVal handler As Socket, ByVal data As [String])
    130.         ' Convert the string data to byte data using ASCII encoding.
    131.         Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
    132.  
    133.         ' Begin sending the data to the remote device.
    134.         handler.BeginSend(byteData, 0, byteData.Length, 0, _
    135.             New AsyncCallback(AddressOf SendCallback), handler)
    136.     End Sub 'Send
    137.  
    138.  
    139.     Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
    140.         Try
    141.             ' Retrieve the socket from the state object.
    142.             Dim handler As Socket = CType(ar.AsyncState, Socket)
    143.  
    144.             ' Complete sending the data to the remote device.
    145.             Dim bytesSent As Integer = handler.EndSend(ar)
    146.             RaiseEvent Status(String.Format("Sent {0} bytes to client.", bytesSent))
    147.  
    148.             handler.Shutdown(SocketShutdown.Both)
    149.             handler.Close()
    150.  
    151.         Catch e As Exception
    152.             RaiseEvent Status(e.ToString())
    153.         End Try
    154.     End Sub 'SendCallback
    155.  
    156.  
    157. End Class 'AsynchronousSocketListener

    I made a few minor changes:
    1) Added 1 Event (Status)
    2) Changed the message display method Console.Write to invoking the Status event


    'Using on a form....

    Add a Listbox Named lstStatus

    VB Code:
    1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    2.          'Wireup status handler....
    3.         AddHandler AsynchronousSocketListener.Status, AddressOf StatusChanged
    4.         AsynchronousSocketListener.StartListening() 'start listening
    5.  
    6.  
    7.     End Sub
    8.  
    9.     Public Sub StatusChanged(ByVal Message As String)
    10.         lstStatus.Items.Add(Message)
    11.     End Sub
    Tips:
    • Google is your friend! Search before posting!
    • Name your thread appropriately... "I Need Help" doesn't cut it!
    • Always post your code!!!! We can't read your mind!!! (well, at least most of us!)
    • Allways Include the Name and Line of the Exception (if one is occuring!)
    • If it is relevant state the version of Visual Studio/.Net Framwork you are using (2002/2003/2005)


    If you think I was helpful, rate my post
    IRC Contact: Rizon/xous ChakraNET/xous Freenode/xous

  4. #4

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2004
    Posts
    610

    Re: Need help on converting apps program

    i am able to run the code, but the interface doesn't display itself.. does it have something to do with the codeS?

  5. #5
    Frenzied Member <ABX's Avatar
    Join Date
    Jul 2002
    Location
    Canada eh...
    Posts
    1,622

    Re: Need help on converting apps program

    Are you tring to connect to it with a client?
    Tips:
    • Google is your friend! Search before posting!
    • Name your thread appropriately... "I Need Help" doesn't cut it!
    • Always post your code!!!! We can't read your mind!!! (well, at least most of us!)
    • Allways Include the Name and Line of the Exception (if one is occuring!)
    • If it is relevant state the version of Visual Studio/.Net Framwork you are using (2002/2003/2005)


    If you think I was helpful, rate my post
    IRC Contact: Rizon/xous ChakraNET/xous Freenode/xous

  6. #6
    Frenzied Member <ABX's Avatar
    Join Date
    Jul 2002
    Location
    Canada eh...
    Posts
    1,622

    Re: Need help on converting apps program

    I didnt relalize that you were keeping this code in a the console project.

    Right click on the project in solution explorer and select properties.

    Change the output type to a Windows Application and set the startup object to the form.

    Please dont ask the same question twice, ask for more help in orginal thread.
    Tips:
    • Google is your friend! Search before posting!
    • Name your thread appropriately... "I Need Help" doesn't cut it!
    • Always post your code!!!! We can't read your mind!!! (well, at least most of us!)
    • Allways Include the Name and Line of the Exception (if one is occuring!)
    • If it is relevant state the version of Visual Studio/.Net Framwork you are using (2002/2003/2005)


    If you think I was helpful, rate my post
    IRC Contact: Rizon/xous ChakraNET/xous Freenode/xous

  7. #7

    Thread Starter
    Fanatic Member
    Join Date
    Dec 2004
    Posts
    610

    Re: Need help on converting apps program

    erm sorry....
    becuase it was another program so i thought i should open another thread.

    the first one is the client i think. and the second one is the server...
    i got these codes from msdn....
    unfortunately.. most codes that they used as examples are for console apps.... do you guyz know why most examples are in console instead of the normal form?

  8. #8
    New Member
    Join Date
    Nov 2006
    Posts
    1

    Re: Need help on converting apps program

    >>I didnt relalize that you were keeping this code in a the console project.

    He is actually using a windows application

    >>i am able to run the code, but the interface doesn't display itself..

    I have the same problem also with your code <ABX
    It does not come back after this line runs from the form load:

    AsynchronousSocketListener.StartListening

    Any suggestions?
    Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width