Страница: 1 |
|
Вопрос: Подскажите аналог Winsock в VB.NET?
|
Добавлено: 22.09.10 23:14
|
|
Автор вопроса: Саня | ICQ: 553816426
|
Здравствуйте форумчане!
Вот, все-таки, решил пересесть на VB.NET с 6-ки, и сразу понял, что придется радикально менять взгляд на казалось бы привычные вещи…
Хочу написать программу для переписки в локальной сети. Раньше в VB6 я для этих целей использовал элемент управления Winsock, а как это реализовать в VB.NET (у меня 2008 студия, хотя это, наверно, не важно), то есть - какой элемент управления или объект используется в VB.NET для подобных задач? Буду очень благодарен за маленький примерчик с пояснениями или ссылку на подобные материалы заранее спасибо.
Ответить
|
Номер ответа: 2 Автор ответа: AgentFire
ICQ: 192496851
Вопросов: 75 Ответов: 3178
|
Профиль | | #2
|
Добавлено: 22.09.10 23:34
|
-
- Public Class Winsock
- Implements IDisposable
-
- Public Class Helper
- Private WaitMs As UInt64
- Private Procedure As Threading.ThreadStart
-
-
-
-
-
-
-
-
- Public Shared Sub RunIn(ByVal Procedure As Threading.ThreadStart, ByVal TimeMs As UInt64, Optional ByVal Parameters As Object = Nothing)
- Dim I As New Helper
- I.WaitMs = TimeMs
- I.Procedure = Procedure
- Dim BW = New BackgroundWorker
- AddHandler BW.DoWork, AddressOf I.BW_Go
- AddHandler BW.RunWorkerCompleted, AddressOf I.BW_Done
- BW.RunWorkerAsync(Parameters)
- End Sub
- Private Sub BW_Go(ByVal sender As Object, ByVal e As DoWorkEventArgs)
- e.Result = e.Argument
- For i As UInt64 = 1 To WaitMs Step Int32.MaxValue
- Dim WaitInterval = If(WaitMs - i > Int32.MaxValue, Int32.MaxValue, Convert.ToInt32(WaitMs - i))
- Threading.Thread.Sleep(WaitInterval)
- Next
- End Sub
- Private Sub BW_Done(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
- Procedure.Invoke()
- CType(sender, BackgroundWorker).Dispose()
- End Sub
- End Class
-
- Friend Const TimeoutIntervalMs As UInt64 = 30000
-
- Public Event OnDataReceive(ByVal Sender As Winsock, ByVal Data As Object)
- Public Event OnConnect(ByVal Sender As Winsock)
- Public Event OnClientAccept(ByVal Sender As Winsock)
- Public Event OnConnectionLost(ByVal Sender As Winsock)
- Public Event OnConnectFail(ByVal Sender As Winsock)
-
- Private TcpListener As Net.Sockets.TcpListener
- Private TcpClient As Net.Sockets.TcpClient
- Private WithEvents BWListener, BWReceiver, BWConnector As BackgroundWorker
- Private nRemoteIP As Net.IPEndPoint
- Private NS As Net.Sockets.NetworkStream, SW As IO.StreamWriter
-
- Private nLastAliveMsg As New Stopwatch
-
- Public ReadOnly Property LocalIPAddresses() As IEnumerable(Of Net.IPAddress)
- Get
- Return From ni In NetworkInterface.GetAllNetworkInterfaces() _
- Where ni.NetworkInterfaceType <> NetworkInterfaceType.Loopback _
- From ipAddress In ni.GetIPProperties.UnicastAddresses _
- Select ipAddress.Address
- End Get
- End Property
- Public ReadOnly Property RemoteIPAddress() As Net.IPAddress
- Get
- Return If(nRemoteIP Is Nothing, Nothing, nRemoteIP.Address)
- End Get
- End Property
- Public ReadOnly Property Listening() As Boolean
- Get
- Return BWListener IsNot Nothing AndAlso BWListener.IsBusy
- End Get
- End Property
- Public ReadOnly Property Connecting() As Boolean
- Get
-
- Return TcpClient IsNot Nothing AndAlso Not TcpClient.Client.Connected
- End Get
- End Property
- Public ReadOnly Property Connected() As Boolean
- Get
- Return TcpClient IsNot Nothing AndAlso TcpClient.Connected
- End Get
- End Property
-
- Public Function Connect(ByVal Address As String, ByVal Port As Int32) As Boolean
- Try
- StopEverything()
- TcpClient = New Net.Sockets.TcpClient
- BWConnector = New System.ComponentModel.BackgroundWorker
- BWConnector.WorkerSupportsCancellation = True
- BWConnector.RunWorkerAsync(New Object() {Address, Port})
- Catch ex As Exception
- Return False
- End Try
- Return True
- End Function
- Private Sub StopBW(ByRef BWs As IEnumerable(Of BackgroundWorker))
- For Each iBW In BWs.Where(Function(T) T IsNot Nothing)
- StopBW(iBW)
- Next
- End Sub
- Private Sub StopBW(ByRef BW As BackgroundWorker)
- BW.CancelAsync()
- BW.Dispose()
- BW = Nothing
- End Sub
- Public Sub StopEverything()
- If SW IsNot Nothing Then
- SW.Close()
- SW.Dispose()
- End If
- If NS IsNot Nothing Then
- NS.Close()
- NS.Dispose()
- End If
-
- StopBW(New BackgroundWorker() {BWReceiver, BWListener, BWConnector})
-
- If TcpListener IsNot Nothing Then
- TcpListener.Stop()
- TcpListener.Server.Close()
- TcpListener = Nothing
- End If
- If TcpClient IsNot Nothing Then
- TcpClient.Close()
- TcpClient = Nothing
- End If
- nRemoteIP = Nothing
-
- GC.Collect()
- End Sub
- Public Function Listen(ByVal Port As Int32) As Boolean
- If Listening OrElse Connected OrElse Connecting Then Return False
-
- Try
- StopEverything()
- TcpListener = New Net.Sockets.TcpListener(Net.IPAddress.Any, Port)
- TcpListener.ExclusiveAddressUse = False
- TcpListener.Start()
-
- If BWListener IsNot Nothing Then BWListener.Dispose()
- BWListener = New System.ComponentModel.BackgroundWorker
- BWListener.WorkerReportsProgress = True
- BWListener.WorkerSupportsCancellation = True
- BWListener.RunWorkerAsync()
- Catch ex As Exception
- Return False
- End Try
-
- Return True
- End Function
-
-
-
-
- Public Function SendData(ByVal Data As Object) As Boolean
- If Data Is Nothing Then Return False
- Try
-
- Dim S = New BinaryFormatter, ByteData() As Byte
- Using Stream = New IO.MemoryStream()
- S.Serialize(Stream, Data)
- ByteData = Stream.ToArray
- End Using
-
-
- SW.WriteLine(Convert.ToBase64String(ByteData))
- SW.Flush()
- Catch ex As Exception
- Return False
- Finally
- GC.Collect()
- End Try
- Return True
- End Function
-
- Private Sub BWListener_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BWListener.DoWork
-
- Try
- Do
- Threading.Thread.Sleep(100)
- Loop Until TcpListener.Pending Or BWListener.CancellationPending
-
- If TcpListener.Pending Then
- e.Result = TcpListener.AcceptTcpClient
- TcpListener.Stop()
- End If
- Catch ex As Exception
- e.Result = Nothing
- End Try
- End Sub
- Private Sub BWListener_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BWListener.RunWorkerCompleted
- If e.Result Is Nothing Then Return
-
-
- Dim TcpClient = CType(e.Result, Net.Sockets.TcpClient)
- StopEverything()
-
- Me.TcpClient = TcpClient
- nRemoteIP = Me.TcpClient.Client.LocalEndPoint
- NS = TcpClient.GetStream
- SW = New IO.StreamWriter(NS)
- RaiseEvent OnClientAccept(Me)
-
- RunReceiver()
- End Sub
-
- Private Sub RunReceiver()
- If BWReceiver IsNot Nothing Then
- BWReceiver.CancelAsync()
- BWReceiver.Dispose()
- End If
-
- AliveSender(False)
-
- BWReceiver = New System.ComponentModel.BackgroundWorker
- BWReceiver.WorkerSupportsCancellation = True
- BWReceiver.WorkerReportsProgress = True
- BWReceiver.RunWorkerAsync()
- End Sub
-
- Private Sub AliveSender(Optional ByVal DoIt As Boolean = True)
- If Timeouted Then
- StopEverything()
- Else
-
- Helper.RunIn(AddressOf AliveSender, 15000)
-
-
- If DoIt AndAlso Connected Then SW.WriteLine("StayAliveMan")
- End If
- End Sub
-
- Private ReadOnly Property Timeouted() As Boolean
- Get
- Return nLastAliveMsg.ElapsedMilliseconds > TimeoutIntervalMs
- End Get
- End Property
-
- Private Sub BWReceiver_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BWReceiver.DoWork
- TcpClient.Client.LingerState.LingerTime = 1000
- TcpClient.Client.LingerState.Enabled = True
-
- Using SR = New IO.StreamReader(NS)
- Try
- Do
-
-
- If NS.DataAvailable Then BWReceiver.ReportProgress(0, SR.ReadLine) Else Threading.Thread.Sleep(100)
- Loop Until BWReceiver.CancellationPending Or Not Connected Or Timeouted
- Catch ex As Exception
-
- e.Result = ex
- End Try
- End Using
- End Sub
- Private Sub BWReceiver_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BWReceiver.ProgressChanged
- Dim Data = CType(e.UserState, String)
- If Data Is Nothing Then Return
- If TypeOf Data Is String AndAlso Data = "StayAliveMan" Then
- nLastAliveMsg = Stopwatch.StartNew
- Return
- End If
-
- Try
- Dim S = New BinaryFormatter
-
- Dim ByteData = Convert.FromBase64String(Data)
-
- Using Stream = New IO.MemoryStream(ByteData, False)
- RaiseEvent OnDataReceive(Me, S.Deserialize(Stream))
- End Using
- Catch ex As Exception
- ;Throw New Exception(String.Format("Deserialization failed: {0}{0}{1}", vbNewLine, ex.Message))
- Finally
- GC.Collect()
- End Try
- End Sub
- Private Sub BWReceiver_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BWReceiver.RunWorkerCompleted
- If BWReceiver IsNot Nothing Then BWReceiver.Dispose()
- StopEverything()
- RaiseEvent OnConnectionLost(Me)
- End Sub
-
- Private Sub BWConnector_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BWConnector.DoWork
- Dim Address = CType(e.Argument(0), String)
- Dim Port = CType(e.Argument(1), Int32)
- Try
- Dim TcpClient = New Net.Sockets.TcpClient
- TcpClient.Connect(Address, Port)
- If TcpClient.Connected Then e.Result = TcpClient Else e.Result = Nothing
- Catch ex As Exception
- e.Result = ex
- End Try
- End Sub
- Private Sub BWConnector_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BWConnector.RunWorkerCompleted
- If BWConnector Is Nothing Then Return
- StopEverything()
-
-
- If TypeOf e.Result Is Net.Sockets.TcpClient Then
- TcpClient = e.Result
- NS = TcpClient.GetStream
- SW = New IO.StreamWriter(NS)
- nRemoteIP = CType(TcpClient.Client.RemoteEndPoint, Net.IPEndPoint)
- RaiseEvent OnConnect(Me)
- RunReceiver()
- Else
- RaiseEvent OnConnectFail(Me)
- End If
-
- End Sub
-
-
- Protected Overridable Sub Dispose(ByVal disposing As Boolean)
- If Not Me.disposedValue Then
- If disposing Then
-
- StopEverything()
- End If
-
-
-
- End If
- Me.disposedValue = True
- End Sub
-
- #Region " IDisposable Support "
- Private disposedValue As Boolean = False
-
-
- Public Sub Dispose() Implements IDisposable.Dispose
-
- Dispose(True)
- GC.SuppressFinalize(Me)
- End Sub
- #End Region
-
- End Class
Ответить
|
Страница: 1 |
Поиск по форуму