Results 1 to 7 of 7

Thread: Error when working with Socket TCP IP (VB.NET)

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2011
    Posts
    10

    Error when working with Socket TCP IP (VB.NET)

    Hi all, this is the first time I try to study the socket of .NET. I configed follow the tutorial here http://msdn.microsoft.com/en-us/library/aa478452.aspx . Then I try to write some execute code for my project. I insert an "Add item" to a listbox after socket server receiving Data from client. However, the server doesn't execute my "Add item" code and it disconnect to the client?
    If I erase this code, everything is ok!

    Is there anybody here can help me resolve this? Thank you very much.
    Best Regards!
    This is a link to my Solution (Clean )
    http://www.mediafire.com/download.php?x3s6e42kr6xm7i2

  2. #2
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Error when working with Socket TCP IP (VB.NET)

    How can you tell that everything is OK if you have erased the code?

  3. #3

    Thread Starter
    New Member
    Join Date
    Jan 2011
    Posts
    10

    Re: Error when working with Socket TCP IP (VB.NET)

    Ah, if I just do all the code follow the link on MSDN. Everything is ok that means Client and Server can send and receive message normally.

    Then, I create a new module on Server project and write some normal code (those code don't effect to socket)

    In OnLineReceived function in frmServer, I insert these code
    vb Code:
    1. Form1.lstStatus.Items.Add("HI")

    The server doesn't execute this code but it disconnect then!
    When I erase this code, ofcourse, everything is ok!

    I just want to catch the data from client and process it for some of my purposes!


    Regards!

  4. #4
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Error when working with Socket TCP IP (VB.NET)

    You should be getting an exception message box telling you why it failed. Most likely it is because Form1 is nothing or lstStatus is nothing. Can you show the error or at least the rest of the code in OnLineReceived method?

  5. #5

    Thread Starter
    New Member
    Join Date
    Jan 2011
    Posts
    10

    Re: Error when working with Socket TCP IP (VB.NET)

    I have rewrite all the code follow MSDN link again http://msdn.microsoft.com/en-us/library/aa478452.aspx
    This is the original code in frmserver
    vb Code:
    1. Imports System.Threading
    2. Imports System.Net
    3. Imports System.Net.Sockets
    4.  
    5. Public Delegate Sub StatusInvoker(ByVal t As String)
    6.  
    7. Public Class Server
    8.     Inherits System.Windows.Forms.Form
    9.  
    10.     Private mobjThread As Thread
    11.     Private mobjListener As TcpListener
    12.     Private mcolClients As New Hashtable()
    13.  
    14. #Region " Windows Form Designer generated code "
    15.  
    16.     Public Sub New()
    17.         MyBase.New()
    18.  
    19.         'This call is required by the Windows Form Designer.
    20.         InitializeComponent()
    21.  
    22.         'Add any initialization after the InitializeComponent() call
    23.  
    24.     End Sub
    25.  
    26.     'Form overrides dispose to clean up the component list.
    27.     Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
    28.         If disposing Then
    29.             If Not (components Is Nothing) Then
    30.                 components.Dispose()
    31.             End If
    32.         End If
    33.         MyBase.Dispose(disposing)
    34.     End Sub
    35.     Friend WithEvents lstStatus As System.Windows.Forms.ListBox
    36.  
    37.     'Required by the Windows Form Designer
    38.     Private components As System.ComponentModel.Container
    39.  
    40.     'NOTE: The following procedure is required by the Windows Form Designer
    41.     'It can be modified using the Windows Form Designer.  
    42.     'Do not modify it using the code editor.
    43.     <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    44.         Me.lstStatus = New System.Windows.Forms.ListBox()
    45.         Me.SuspendLayout()
    46.         '
    47.         'lstStatus
    48.         '
    49.         Me.lstStatus.Dock = System.Windows.Forms.DockStyle.Fill
    50.         Me.lstStatus.Location = New System.Drawing.Point(0, 0)
    51.         Me.lstStatus.Name = "lstStatus"
    52.         Me.lstStatus.Size = New System.Drawing.Size(292, 273)
    53.         Me.lstStatus.TabIndex = 0
    54.         '
    55.         'Form1
    56.         '
    57.         Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
    58.         Me.ClientSize = New System.Drawing.Size(292, 273)
    59.         Me.Controls.Add(Me.lstStatus)
    60.         Me.Name = "Form1"
    61.         Me.Text = "Socket Server"
    62.         Me.ResumeLayout(False)
    63.  
    64.     End Sub
    65.  
    66. #End Region
    67.  
    68.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    69.         mobjThread = New Thread(AddressOf DoListen)
    70.         mobjThread.Start()
    71.         UpdateStatus("Listener started")
    72.         Form2.Show()
    73.         Focus()
    74.     End Sub
    75.  
    76.     Private Sub DoListen()
    77.         Try
    78.             mobjListener = New TcpListener(5000)
    79.  
    80.             mobjListener.Start()
    81.             Do
    82.                 'Dim x As New Client(mobjListener.AcceptSocket)
    83.                 Dim x As New Client(mobjListener.AcceptTcpClient)
    84.  
    85.                 AddHandler x.Connected, AddressOf OnConnected
    86.                 AddHandler x.Disconnected, AddressOf OnDisconnected
    87.                 'AddHandler x.CharsReceived, AddressOf OnCharsReceived
    88.                 AddHandler x.LineReceived, AddressOf OnLineReceived
    89.                 mcolClients.Add(x.ID, x)
    90.                 Dim params() As Object = {"New connection"}
    91.                 Me.Invoke(New StatusInvoker(AddressOf Me.UpdateStatus), params)
    92.             Loop Until False
    93.         Catch
    94.         End Try
    95.     End Sub
    96.  
    97.     Private Sub OnConnected(ByVal sender As Client)
    98.         UpdateStatus("Connected")
    99.     End Sub
    100.  
    101.     Private Sub OnDisconnected(ByVal sender As Client)
    102.         UpdateStatus("Disconnected")
    103.         mcolClients.Remove(sender.ID)
    104.     End Sub
    105.  
    106.     'Private Sub OnCharsReceived(ByVal sender As Client, ByVal Data As String)
    107.     '  UpdateStatus("Chars:" & Data)
    108.     'End Sub
    109.  
    110.     Private Sub OnLineReceived(ByVal sender As Client, ByVal Data As String)
    111.         Try
    112.             UpdateStatus("Line:" & Data)
    113.  
    114.             Dim objClient As Client
    115.             Dim d As DictionaryEntry
    116.  
    117.             For Each d In mcolClients
    118.                 objClient = d.Value
    119.                 objClient.Send(Data & vbCrLf)
    120.             Next
    121.         Catch ex As Exception
    122.             MsgBox(ex.Message)
    123.         End Try
    124.     End Sub
    125.  
    126.     Private Sub UpdateStatus(ByVal t As String)
    127.         lstStatus.Items.Add(t)
    128.         lstStatus.SetSelected(lstStatus.Items.Count - 1, True)
    129. Form2.listbox1.items.add("Test")
    130.     End Sub
    131.  
    132.     Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
    133.         mobjListener.Stop()
    134.     End Sub
    135. End Class


    So if you run this solution (follows origin of MSDN) everything is very ok. As you seen on the Sub UpdateStatus above, I inserted Form2.listbox1.items.add("Test") to add new item to a form also on Server project. However, the Sub UpdateStatus just add item to lstStatus (this listbox is in frmServer itself), the Sub doesn't add item to listbox1 on form2. No error shows when I Try Catch!
    I think I cannot add new items to a listbox outside of frmServer?!!!

    How can I resolve this?

  6. #6
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Error when working with Socket TCP IP (VB.NET)

    The TryCatch is used to deal with the exception, if you are doing nothing within the TryCatch then it will of course do nothing with the exception, so no error will be shown. I need to see the error like so!!

    Code:
    Try
      Form2.listbox1.items.add("Test")
    Catch ex As Exception
       MessageBox.Show(ex.ToString)
    End Try
    I can guess that you have a problem already just by the fact that 'items' and 'add' are in lower case, they should have been fixed by the editor to uppercase. Put this at the TOP of this file if you do not already have it.

    Code:
    Option Strict On
    Option Explicit On

  7. #7

    Thread Starter
    New Member
    Join Date
    Jan 2011
    Posts
    10

    Re: Error when working with Socket TCP IP (VB.NET)

    This is my new frmServer form code
    vb.net Code:
    1. Option Strict On
    2. Option Explicit On
    3. Imports System.Net.Sockets
    4. Imports System.Threading
    5. Imports System.Runtime.InteropServices
    6.  
    7. Public Class frmServer
    8.     Public Delegate Sub StatusInvoker(ByVal t As String)
    9.     Private mobjThread As Thread
    10.     Private mobjListener As TcpListener
    11.     Private mcolClients As New Hashtable()
    12.     Public IPAddr As String
    13.     Public PCName As String
    14.     Public Msg As String
    15.     Public UserID As String
    16.     Public PassW As String
    17.     Public Stat As String
    18.  
    19. #Region "Chuyển Số Liệu Về FrmMain form"
    20.     'Check xem IP có đc add chưa, có rồi thì khỏi add nữa
    21.     Public Sub AddIP()
    22.  
    23.     End Sub
    24. #End Region
    25.  
    26.     Private Function GetIPAddress() As String
    27.         Dim strHostName As String
    28.         strHostName = System.Net.Dns.GetHostName()
    29.         GetIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()
    30.     End Function
    31.  
    32.     Private Sub UpdateStatus(ByVal t As String)
    33.         Try
    34.             MsgBox(t)
    35.             If t.Length > 20 Then
    36.                 CodeFilter(t)
    37.                 MsgProcess(Msg)
    38.             End If
    39.         Catch ex As Exception
    40.             MsgBox(ex.Message)
    41.         End Try
    42.     End Sub
    43.  
    44.     Private Sub DoListen()
    45.         Try
    46.             mobjListener = New TcpListener(7799)
    47.  
    48.             mobjListener.Start()
    49.             Do
    50.                 Dim x As New Client(mobjListener.AcceptTcpClient)
    51.  
    52.                 AddHandler x.Connected, AddressOf OnConnected
    53.                 AddHandler x.Disconnected, AddressOf OnDisconnected
    54.                 AddHandler x.LineReceived, AddressOf OnLineReceived
    55.                 mcolClients.Add(x.ID, x)
    56.  
    57.                 Dim params() As Object = {"New connection"}
    58.                 Me.Invoke(New StatusInvoker(AddressOf Me.UpdateStatus), params)
    59.             Loop Until False
    60.         Catch
    61.         End Try
    62.     End Sub
    63.  
    64.     Private Sub frmServer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    65.         ipServer.Value = GetIPAddress()
    66.         mobjThread = New Threading.Thread(AddressOf DoListen)
    67.         mobjThread.SetApartmentState(ApartmentState.STA)
    68.         mobjThread.Start()
    69.         'StartThread()
    70.         UpdateStatus("Listener started")
    71.     End Sub
    72.     Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
    73.         mobjListener.Stop()
    74.     End Sub
    75.  
    76.     Private Sub OnConnected(ByVal sender As Client)
    77.         UpdateStatus("Connected")
    78.     End Sub
    79.  
    80.     Private Sub OnDisconnected(ByVal sender As Client)
    81.         UpdateStatus("Disconnected")
    82.         mcolClients.Remove(sender.ID)
    83.     End Sub
    84.  
    85.     Private Sub OnLineReceived(ByVal sender As Client, ByVal Data As String)
    86.         UpdateStatus(Data)
    87.  
    88.         Dim objClient As Client
    89.         Dim d As DictionaryEntry
    90.  
    91.         For Each d In mcolClients
    92.             objClient = CType(d.Value, Client)
    93.             objClient.Send(Data & vbCrLf)
    94.         Next
    95.     End Sub
    96.  
    97.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    98.         CodeFilter("ip:192.1.243.123 -name:May_01 -code:001# -acct:001|Xc9e")
    99.         'MsgProcess(Msg)
    100.         MsgBox(IPAddr & PCName & Msg & UserID & PassW)
    101.         'MsgBox(CheckUserAccount("", ""))
    102.     End Sub
    103.  
    104. #Region "Process Lan Connection"
    105.     'Xử lý các mã Msg
    106.     <STAThread()>
    107.     Public Sub MsgProcess(ByVal Msg As String)
    108.         Select Case Msg
    109.             Case Is = "000"
    110.                 'Client disconnected
    111.                 RemoveClient(PCName)
    112.                 Stat = "Đã Kết Nối"
    113.                 Exit Sub
    114.             Case Is = "001"
    115.                 'Client connected
    116.                 AddClient()
    117.  
    118.         End Select
    119.     End Sub
    120.  
    121.     'Add ListConnect item
    122.     <STAThread()> _
    123.     Public Sub AddClient()
    124.         Dim item As New ListViewItem
    125.         item.Text = CStr(lstStatus.Items.Count + 1) 'số thứ tự
    126.         item.SubItems.Add(PCName)
    127.         item.SubItems.Add(IPAddr)
    128.         For i As Integer = 0 To frmMain.listScore.Items.Count - 1
    129.             If UserID = frmMain.listScore.Items(i).Text Then
    130.                 item.SubItems.Add(frmMain.listScore.Items(i).SubItems(1)) 'thêm tên thí sinh
    131.                 Exit For
    132.             End If
    133.         Next
    134.         item.SubItems.Add(UserID)
    135.         item.SubItems.Add(Stat)
    136.         lstStatus.Items.Add(item)
    137.     End Sub
    138.  
    139.     'Remove ListConnect item
    140.     Public Sub RemoveClient(ByVal Name As String)
    141.         With frmMain
    142.             If .listConnect.Items.Count <> 0 Then
    143.                 For i As Integer = 0 To .listConnect.Items.Count - 1
    144.                     If Name = .listConnect.Items(i).SubItems(0).Text Then
    145.                         .listConnect.Items(i).Remove()
    146.                         Exit Sub
    147.                     End If
    148.                 Next
    149.             End If
    150.         End With
    151.     End Sub
    152.  
    153.     'Check xem IP đã đc add vô listConnect chưa
    154.     Public Function CheckNewIP(ByVal IP As String) As Boolean
    155.         With frmMain
    156.             If .listConnect.Items.Count = 0 Then
    157.                 Return False
    158.             Else
    159.                 For i As Integer = 0 To .listConnect.Items.Count - 1
    160.                     If IP = .listConnect.Items(i).SubItems(0).Text Then
    161.                         Return True
    162.                         Exit Function
    163.                     Else
    164.                         Return False
    165.                     End If
    166.                 Next
    167.             End If
    168.         End With
    169.     End Function
    170.  
    171.     'Lọc các thông tin ra khỏi Message
    172.     Public Sub CodeFilter(ByVal code As String)
    173.         Dim firstspace As Byte = CByte(InStr(1, code, " "))
    174.         IPAddr = Strings.Mid(code, 4, firstspace - 4)
    175.         Dim secondspace As Byte = CByte(InStr(firstspace + 1, code, " "))
    176.         PCName = Strings.Mid(code, firstspace + 7, secondspace - firstspace - 7)
    177.         Dim thirdspace As Byte = CByte(InStr(secondspace + 1, code, "#"))
    178.         Msg = Strings.Mid(code, secondspace + 7, thirdspace - secondspace - 7)
    179.         Dim lastpoint As Byte = CByte(InStr(thirdspace + 1, code, "|"))
    180.         UserID = Strings.Mid(code, thirdspace + 8, lastpoint - thirdspace - 8)
    181.         If lastpoint < code.Length Then
    182.             'Have password
    183.             PassW = Strings.Right(code, code.Length - lastpoint)
    184.         Else
    185.             PassW = ""
    186.         End If
    187.     End Sub
    188.  
    189.     Public Function CheckUserAccount(ByVal UID As String, ByVal UPW As String) As Boolean
    190.         With frmMain.listScore
    191.             Dim RightID As Boolean = False
    192.             Dim RightPW As Boolean = False
    193.             If frmMain.chkSetPassword.Checked = True Then
    194.                 For i As Integer = 0 To .Items.Count - 1
    195.                     If UPW = .Items(i).SubItems(.Columns.Count - 1).Text Then
    196.                         RightPW = True
    197.                         Exit For
    198.                     End If
    199.                 Next
    200.                 If RightPW = False Then Return False 'Sai pass thì ko cần duyệt USER NAME
    201.             End If
    202.             MsgBox("UHM")
    203.             For i As Integer = 0 To .Items.Count - 1
    204.                 If UID = .Items(i).Text Then
    205.                     RightID = True
    206.                     Exit For
    207.                 End If
    208.             Next
    209.             If RightID And RightPW = True Then
    210.                 Return True
    211.             Else
    212.                 Return False
    213.             End If
    214.         End With
    215.     End Function
    216.  
    217.     Public Function CheckUserPassW(ByVal UPW As String) As Boolean
    218.         With frmMain.listScore
    219.             Dim SubItemIndex As Integer
    220.             If frmMain.chkSetPassword.Checked = False Then
    221.                 Return True
    222.             Else
    223.                 For i As Integer = 0 To .Items.Count - 1
    224.                     If UPW = .Items(i).SubItems(.Columns.Count - 1).Text Then
    225.                         Return True
    226.                         Exit Function
    227.                     End If
    228.                 Next
    229.                 Return False
    230.             End If
    231.         End With
    232.     End Function
    233. #End Region
    234. End Classn
    Yah! Because I cannot add to a list outsite of frmServer form. Therefore, I rewrite to add to lstStatus of frmServer.
    When I run, it has show the Microsoft .NET Framwork error
    See the end of this message for details on invoking
    just-in-time (JIT) debugging instead of this dialog box.

    ************** Exception Text **************
    System.InvalidOperationException: DragDrop registration did not succeed. ---> System.Threading.ThreadStateException: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.
    at System.Windows.Forms.Control.SetAcceptDrops(Boolean accept)
    --- End of inner exception stack trace ---
    at System.Windows.Forms.Control.SetAcceptDrops(Boolean accept)
    at System.Windows.Forms.Control.OnHandleCreated(EventArgs e)
    at DevComponents.AdvTree.AdvTree.OnHandleCreated(EventArgs e)
    at System.Windows.Forms.Control.WmCreate(Message& m)
    at System.Windows.Forms.Control.WndProc(Message& m)
    at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    Then I press the continue button on the Error Message, the sub add item to lstStatus (on sub UpdateStatus (byval t as string)) is executed successully.
    However, because I see this error, I don't know what error affect to my result?

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