Visual Basic, .NET, ASP, VBScript
 

   
   
     

Форум - .NET

Страница: 1 |

 

  Вопрос: Подскажите аналог Winsock в VB.NET? Добавлено: 22.09.10 23:14  

Автор вопроса:  Саня | ICQ: 553816426 
Здравствуйте форумчане!
Вот, все-таки, решил пересесть на VB.NET с 6-ки, и сразу понял, что придется радикально менять взгляд на казалось бы привычные вещи…
Хочу написать программу для переписки в локальной сети. Раньше в VB6 я для этих целей использовал элемент управления Winsock, а как это реализовать в VB.NET (у меня 2008 студия, хотя это, наверно, не важно), то есть - какой элемент управления или объект используется в VB.NET для подобных задач? Буду очень благодарен за маленький примерчик с пояснениями или ссылку на подобные материалы заранее спасибо.

Ответить

  Ответы Всего ответов: 7  

Номер ответа: 1
Автор ответа:
 EROS



Вопросов: 58
Ответов: 4255
 Профиль | | #1 Добавлено: 22.09.10 23:23
TcpClient
TcpListner

Ответить

Номер ответа: 2
Автор ответа:
 AgentFire



ICQ: 192496851 

Вопросов: 75
Ответов: 3178
 Профиль | | #2 Добавлено: 22.09.10 23:34
  1.  
  2. Public Class Winsock
  3.     Implements IDisposable
  4.  
  5.     Public Class Helper
  6.         Private WaitMs As UInt64
  7.         Private Procedure As Threading.ThreadStart
  8.  
  9.         ''' <summary>
  10.         ''' Waits specified time period in milliseconds with maximum of UInt64.MaxValue
  11.         ''' and then runs teh specified procedure
  12.         ''' </summary>
  13.         ''' <param name="Procedure">The procedure to run when the wait time is over</param>
  14.         ''' <param name="TimeMs">Time period to wait</param>
  15.         ''' <param name="Parameters">Currently useless</param>
  16.         Public Shared Sub RunIn(ByVal Procedure As Threading.ThreadStart, ByVal TimeMs As UInt64, Optional ByVal Parameters As Object = Nothing)
  17.             Dim I As New Helper
  18.             I.WaitMs = TimeMs
  19.             I.Procedure = Procedure
  20.             Dim BW = New BackgroundWorker
  21.             AddHandler BW.DoWork, AddressOf I.BW_Go
  22.             AddHandler BW.RunWorkerCompleted, AddressOf I.BW_Done
  23.             BW.RunWorkerAsync(Parameters)
  24.         End Sub
  25.         Private Sub BW_Go(ByVal sender As Object, ByVal e As DoWorkEventArgs)
  26.             e.Result = e.Argument
  27.             For i As UInt64 = 1 To WaitMs Step Int32.MaxValue
  28.                 Dim WaitInterval = If(WaitMs - i > Int32.MaxValue, Int32.MaxValue, Convert.ToInt32(WaitMs - i))
  29.                 Threading.Thread.Sleep(WaitInterval)
  30.             Next
  31.         End Sub
  32.         Private Sub BW_Done(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
  33.             Procedure.Invoke()
  34.             CType(sender, BackgroundWorker).Dispose()
  35.         End Sub
  36.     End Class
  37.  
  38.     Friend Const TimeoutIntervalMs As UInt64 = 30000
  39.  
  40.     Public Event OnDataReceive(ByVal Sender As Winsock, ByVal Data As Object)
  41.     Public Event OnConnect(ByVal Sender As Winsock)
  42.     Public Event OnClientAccept(ByVal Sender As Winsock)
  43.     Public Event OnConnectionLost(ByVal Sender As Winsock)
  44.     Public Event OnConnectFail(ByVal Sender As Winsock)
  45.  
  46.     Private TcpListener As Net.Sockets.TcpListener
  47.     Private TcpClient As Net.Sockets.TcpClient
  48.     Private WithEvents BWListener, BWReceiver, BWConnector As BackgroundWorker
  49.     Private nRemoteIP As Net.IPEndPoint
  50.     Private NS As Net.Sockets.NetworkStream, SW As IO.StreamWriter
  51.  
  52.     Private nLastAliveMsg As New Stopwatch
  53.  
  54.     Public ReadOnly Property LocalIPAddresses() As IEnumerable(Of Net.IPAddress)
  55.         Get
  56.             Return From ni In NetworkInterface.GetAllNetworkInterfaces() _
  57.                    Where ni.NetworkInterfaceType <> NetworkInterfaceType.Loopback _
  58.                    From ipAddress In ni.GetIPProperties.UnicastAddresses _
  59.                    Select ipAddress.Address
  60.         End Get
  61.     End Property
  62.     Public ReadOnly Property RemoteIPAddress() As Net.IPAddress
  63.         Get
  64.             Return If(nRemoteIP Is Nothing, Nothing, nRemoteIP.Address)
  65.         End Get
  66.     End Property
  67.     Public ReadOnly Property Listening() As Boolean
  68.         Get
  69.             Return BWListener IsNot Nothing AndAlso BWListener.IsBusy
  70.         End Get
  71.     End Property
  72.     Public ReadOnly Property Connecting() As Boolean
  73.         Get
  74.             'we exist and we still not connected means we ARE connecting
  75.             Return TcpClient IsNot Nothing AndAlso Not TcpClient.Client.Connected
  76.         End Get
  77.     End Property
  78.     Public ReadOnly Property Connected() As Boolean
  79.         Get
  80.             Return TcpClient IsNot Nothing AndAlso TcpClient.Connected
  81.         End Get
  82.     End Property
  83.  
  84.     Public Function Connect(ByVal Address As String, ByVal Port As Int32) As Boolean
  85.         Try
  86.             StopEverything()
  87.             TcpClient = New Net.Sockets.TcpClient 'just to know if we are connecting here
  88.             BWConnector = New System.ComponentModel.BackgroundWorker
  89.             BWConnector.WorkerSupportsCancellation = True
  90.             BWConnector.RunWorkerAsync(New Object() {Address, Port})
  91.         Catch ex As Exception
  92.             Return False
  93.         End Try
  94.         Return True
  95.     End Function
  96.     Private Sub StopBW(ByRef BWs As IEnumerable(Of BackgroundWorker))
  97.         For Each iBW In BWs.Where(Function(T) T IsNot Nothing)
  98.             StopBW(iBW)
  99.         Next
  100.     End Sub
  101.     Private Sub StopBW(ByRef BW As BackgroundWorker)
  102.         BW.CancelAsync()
  103.         BW.Dispose()
  104.         BW = Nothing
  105.     End Sub
  106.     Public Sub StopEverything()
  107.         If SW IsNot Nothing Then
  108.             SW.Close()
  109.             SW.Dispose()
  110.         End If
  111.         If NS IsNot Nothing Then
  112.             NS.Close()
  113.             NS.Dispose()
  114.         End If
  115.  
  116.         StopBW(New BackgroundWorker() {BWReceiver, BWListener, BWConnector})
  117.  
  118.         If TcpListener IsNot Nothing Then
  119.             TcpListener.Stop()
  120.             TcpListener.Server.Close()
  121.             TcpListener = Nothing
  122.         End If
  123.         If TcpClient IsNot Nothing Then
  124.             TcpClient.Close()
  125.             TcpClient = Nothing
  126.         End If
  127.         nRemoteIP = Nothing
  128.  
  129.         GC.Collect()
  130.     End Sub
  131.     Public Function Listen(ByVal Port As Int32) As Boolean
  132.         If Listening OrElse Connected OrElse Connecting Then Return False
  133.  
  134.         Try
  135.             StopEverything()
  136.             TcpListener = New Net.Sockets.TcpListener(Net.IPAddress.Any, Port)
  137.             TcpListener.ExclusiveAddressUse = False
  138.             TcpListener.Start()
  139.  
  140.             If BWListener IsNot Nothing Then BWListener.Dispose()
  141.             BWListener = New System.ComponentModel.BackgroundWorker
  142.             BWListener.WorkerReportsProgress = True
  143.             BWListener.WorkerSupportsCancellation = True
  144.             BWListener.RunWorkerAsync()
  145.         Catch ex As Exception
  146.             Return False
  147.         End Try
  148.  
  149.         Return True
  150.     End Function
  151.     ''' <summary>
  152.     ''' Sends serialized object. All the objects inside must be serializable.
  153.     ''' All the outcoming data should be located in the same root namespace as the clients'
  154.     ''' </summary>
  155.     Public Function SendData(ByVal Data As Object) As Boolean
  156.         If Data Is Nothing Then Return False
  157.         Try
  158.             'Serializing
  159.             Dim S = New BinaryFormatter, ByteData() As Byte
  160.             Using Stream = New IO.MemoryStream()
  161.                 S.Serialize(Stream, Data)
  162.                 ByteData = Stream.ToArray
  163.             End Using
  164.  
  165.             'Sending converted
  166.             SW.WriteLine(Convert.ToBase64String(ByteData))
  167.             SW.Flush()
  168.         Catch ex As Exception
  169.             Return False
  170.         Finally
  171.             GC.Collect()
  172.         End Try
  173.         Return True
  174.     End Function
  175.  
  176.     Private Sub BWListener_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BWListener.DoWork
  177.         'Listening until it comes
  178.         Try
  179.             Do
  180.                 Threading.Thread.Sleep(100)
  181.             Loop Until TcpListener.Pending Or BWListener.CancellationPending
  182.  
  183.             If TcpListener.Pending Then
  184.                 e.Result = TcpListener.AcceptTcpClient
  185.                 TcpListener.Stop()
  186.             End If
  187.         Catch ex As Exception
  188.             e.Result = Nothing
  189.         End Try
  190.     End Sub
  191.     Private Sub BWListener_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BWListener.RunWorkerCompleted
  192.         If e.Result Is Nothing Then Return
  193.  
  194.         'Got a connection!
  195.         Dim TcpClient = CType(e.Result, Net.Sockets.TcpClient)
  196.         StopEverything()
  197.  
  198.         Me.TcpClient = TcpClient
  199.         nRemoteIP = Me.TcpClient.Client.LocalEndPoint
  200.         NS = TcpClient.GetStream
  201.         SW = New IO.StreamWriter(NS)
  202.         RaiseEvent OnClientAccept(Me)
  203.  
  204.         RunReceiver()
  205.     End Sub
  206.  
  207.     Private Sub RunReceiver()
  208.         If BWReceiver IsNot Nothing Then
  209.             BWReceiver.CancelAsync()
  210.             BWReceiver.Dispose()
  211.         End If
  212.  
  213.         AliveSender(False)
  214.  
  215.         BWReceiver = New System.ComponentModel.BackgroundWorker
  216.         BWReceiver.WorkerSupportsCancellation = True
  217.         BWReceiver.WorkerReportsProgress = True
  218.         BWReceiver.RunWorkerAsync()
  219.     End Sub
  220.  
  221.     Private Sub AliveSender(Optional ByVal DoIt As Boolean = True)
  222.         If Timeouted Then
  223.             StopEverything()
  224.         Else
  225.             'Registers slow-bomb pseudo-recursia on this procedure %)
  226.             Helper.RunIn(AddressOf AliveSender, 15000)
  227.  
  228.             'Sends keep-alive packet if we are already in
  229.             If DoIt AndAlso Connected Then SW.WriteLine("StayAliveMan")
  230.         End If
  231.     End Sub
  232.  
  233.     Private ReadOnly Property Timeouted() As Boolean
  234.         Get
  235.             Return nLastAliveMsg.ElapsedMilliseconds > TimeoutIntervalMs
  236.         End Get
  237.     End Property
  238.  
  239.     Private Sub BWReceiver_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BWReceiver.DoWork
  240.         TcpClient.Client.LingerState.LingerTime = 1000
  241.         TcpClient.Client.LingerState.Enabled = True
  242.  
  243.         Using SR = New IO.StreamReader(NS)
  244.             Try
  245.                 Do
  246.                     'Hanging until we got a string &
  247.                     'Reporting received data
  248.                     If NS.DataAvailable Then BWReceiver.ReportProgress(0, SR.ReadLine) Else Threading.Thread.Sleep(100)
  249.                 Loop Until BWReceiver.CancellationPending Or Not Connected Or Timeouted
  250.             Catch ex As Exception
  251.                 'Connection lost
  252.                 e.Result = ex
  253.             End Try
  254.         End Using
  255.     End Sub
  256.     Private Sub BWReceiver_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BWReceiver.ProgressChanged
  257.         Dim Data = CType(e.UserState, String)
  258.         If Data Is Nothing Then Return
  259.         If TypeOf Data Is String AndAlso Data = "StayAliveMan" Then
  260.             nLastAliveMsg = Stopwatch.StartNew
  261.             Return
  262.         End If
  263.  
  264.         Try
  265.             Dim S = New BinaryFormatter
  266.             'Unconvert
  267.             Dim ByteData = Convert.FromBase64String(Data)
  268.             'Deserialize
  269.             Using Stream = New IO.MemoryStream(ByteData, False)
  270.                 RaiseEvent OnDataReceive(Me, S.Deserialize(Stream))
  271.             End Using
  272.         Catch ex As Exception
  273.             ;Throw New Exception(String.Format("Deserialization failed: {0}{0}{1}", vbNewLine, ex.Message))
  274.         Finally
  275.             GC.Collect()
  276.         End Try
  277.     End Sub
  278.     Private Sub BWReceiver_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BWReceiver.RunWorkerCompleted
  279.         If BWReceiver IsNot Nothing Then BWReceiver.Dispose()
  280.         StopEverything()
  281.         RaiseEvent OnConnectionLost(Me)
  282.     End Sub
  283.  
  284.     Private Sub BWConnector_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BWConnector.DoWork
  285.         Dim Address = CType(e.Argument(0), String)     'ip
  286.         Dim Port = CType(e.Argument(1), Int32)         'port
  287.         Try
  288.             Dim TcpClient = New Net.Sockets.TcpClient
  289.             TcpClient.Connect(Address, Port)
  290.             If TcpClient.Connected Then e.Result = TcpClient Else e.Result = Nothing
  291.         Catch ex As Exception
  292.             e.Result = ex
  293.         End Try
  294.     End Sub
  295.     Private Sub BWConnector_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BWConnector.RunWorkerCompleted
  296.         If BWConnector Is Nothing Then Return
  297.         StopEverything()
  298.  
  299.         'if we really connected
  300.         If TypeOf e.Result Is Net.Sockets.TcpClient Then
  301.             TcpClient = e.Result
  302.             NS = TcpClient.GetStream
  303.             SW = New IO.StreamWriter(NS)
  304.             nRemoteIP = CType(TcpClient.Client.RemoteEndPoint, Net.IPEndPoint)
  305.             RaiseEvent OnConnect(Me)
  306.             RunReceiver()
  307.         Else
  308.             RaiseEvent OnConnectFail(Me)
  309.         End If
  310.  
  311.     End Sub
  312.  
  313.     ' IDisposable
  314.     Protected Overridable Sub Dispose(ByVal disposing As Boolean)
  315.         If Not Me.disposedValue Then
  316.             If disposing Then
  317.                 ' TODO: free other state (managed objects).
  318.                 StopEverything()
  319.             End If
  320.  
  321.             ' TODO: free your own state (unmanaged objects).
  322.             ' TODO: set large fields to null.
  323.         End If
  324.         Me.disposedValue = True
  325.     End Sub
  326.  
  327. #Region " IDisposable Support "
  328.     Private disposedValue As Boolean = False 'To detect redundant calls
  329.  
  330.     ' This code added by Visual Basic to correctly implement the disposable pattern.
  331.     Public Sub Dispose() Implements IDisposable.Dispose
  332.         ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
  333.         Dispose(True)
  334.         GC.SuppressFinalize(Me)
  335.     End Sub
  336. #End Region
  337.  
  338. End Class

Ответить

Номер ответа: 3
Автор ответа:
 Саня



ICQ: 553816426 

Вопросов: 10
Ответов: 99
 Профиль | | #3 Добавлено: 22.09.10 23:36
Спасибо!!!
TcpClient это то что нужно, а вот TcpListner в обозреватели объектов не нашел. Что это?

Ответить

Номер ответа: 4
Автор ответа:
 Саня



ICQ: 553816426 

Вопросов: 10
Ответов: 99
 Профиль | | #4 Добавлено: 22.09.10 23:37
 AgentFire А вот за это ОГРОМНАЯ благодарочка!!!

Ответить

Номер ответа: 5
Автор ответа:
 EROS



Вопросов: 58
Ответов: 4255
 Профиль | | #5 Добавлено: 22.09.10 23:42
TcpListner - это "слушатель". Он принимает подключения и читает данные с канала.. это, по сути, серверная часть

Ответить

Номер ответа: 6
Автор ответа:
 Саня



ICQ: 553816426 

Вопросов: 10
Ответов: 99
 Профиль | | #6 Добавлено: 22.09.10 23:48
Понял спасибо. Ща будем разбираться: пробовать, гуглить, тестировать... Но думаю представленного выше класса будет достаточно.
Благодарю за отзывчивость.

Ответить

Номер ответа: 7
Автор ответа:
 AgentFire



ICQ: 192496851 

Вопросов: 75
Ответов: 3178
 Профиль | | #7 Добавлено: 23.09.10 10:02
что, помогло? )

Ответить

Страница: 1 |

Поиск по форуму



© Copyright 2002-2011 VBNet.RU | Пишите нам