sockets

  • Thread starter Michael Maercker
  • Start date
M

Michael Maercker

hi!

i'm really not into networking at all and have now been asigned the task of
porting a vb6-code into vb.net (compact framework, in this case) and the
code uses the winsock-control. i quickly found out that .net uses
system.net.sockets.socket or .tcpclient/.tcpserver. and these confuse me...
:blush:| and help would be really great! links, code, wrappers, tips,
whateveryougot...

one of my main problems, i guess, is: why don't sockets raise events like
mysock_gotdata()?! (or like vb6's winsock...) wouldn't that be usefull in
any case? why not have it as part of the framework?

i found sample code where the "receiving" is done in a "while true" loop -
with no exit; except possibly by catching an error, which was done outside
the loop (but i don't think so). wouldn't the program "hang" in it's endless
loop? i found no sign of or any comment on any "multi-threading", but i'm
reallyreally not into that - is it part of the solution?

coming freshly from vb6, vb.net is a joy! with quick and cool results...
....and now this ;o]...

thanks,
m.
 
B

Brian Mitchell

I'm pretty new at sockets like you but what I found is that some of the
calls (like updclient.receive) is a blocking call which just assigns the
socket data to an object. I don't use much of the TCP but I would assume it
would be similar with the blocking. I also use an endless loop to receive
the data and simply put the procedure in a thread. Every time I run into an
error it does stop inside the thread and I use the try..catch to trap it

Probably didn't do much to answer your question...just my 2cents.
 
S

Supra

Option Explicit On
Option Strict Off

Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Public Class StateObject
Public workSocket As Socket = Nothing
Public BufferSize As Integer = 32767
Public buffer(32767) As Byte
Public sb As New StringBuilder
End Class

Public Class SockFactory
Public Event onConnect()
Public Event onError(ByVal Description As String)
'Public Event onDataArrival(ByVal Data As Byte(), ByVal
TotalBytes As Integer)
Public Event onDataArrival(ByVal Data As String, ByVal
TotalBytes As Integer)
Public Event onDisconnect()
Public Event onSendComplete(ByVal DataSize As Integer)

Private Shared Response As [String] = [String].Empty
Private Shared Port As Integer = 44
Private Shared ipHostInfo As IPHostEntry = Dns.Resolve("localhost")
Private Shared ipAddress As ipAddress = ipHostInfo.AddressList(0)
Private Shared Client As New Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)
Dim clsReader As New PirateChat.clsReadWriteXML
Public bConnected As Boolean
Private mConnected As Boolean


#Region "Socketconnted "
Private Sub sockConnected(ByVal ar As IAsyncResult)
Try
If Client.Connected = False Then RaiseEvent
onError("Connection refused.") : Exit Sub
Dim state As New StateObject
state.workSocket = Client
Client.BeginReceive(state.buffer, 0, state.BufferSize,
0, AddressOf sockDataArrival, state)
RaiseEvent onConnect()
Catch
RaiseEvent onError(Err.Description)
Exit Sub
End Try
End Sub
#End Region
#Region " DataArrival "

Private Sub sockDataArrival(ByVal ar As IAsyncResult)
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim client As Socket = state.workSocket
Dim bytesRead As Integer
' If mConnected = True Then Exit Sub
Try
bytesRead = client.EndReceive(ar)
Catch
Exit Sub
End Try

Try
Dim Data() As Byte = state.buffer
If bytesRead = 0 Then
client.Shutdown(SocketShutdown.Both)
client.Close()
RaiseEvent onDisconnect()
Exit Sub
End If
ReDim state.buffer(32767)

client.BeginReceive(state.buffer, 0, state.BufferSize,
0, AddressOf sockDataArrival, state)
RaiseEvent
onDataArrival(ASCIIEncoding.ASCII.GetString(Data), bytesRead)
Catch
RaiseEvent onError(Err.Description)
Exit Sub
End Try

End Sub
#End Region
#Region "Connect "
'Socket programming in .NET is made possible by the Socket class
present inside the System.Net.Sockets namespace. This Socket class has
several method and properties and a constructor. The first step is to
create an object of this class. Since there is only one constructor we
have no choice but to use it.
'The first parameter is the address family which we will use, in
this case, interNetwork (which is IP version 4) - other options include
Banyan NetBios, AppleTalk etc. (AddressFamily is an enum defined in
Sockets namespace). Next we need to specify socket type: and we would
use reliable two way connection-based sockets (stream) instead of
un-reliable Connectionless sockets (datagrams) . So we obviously specify
stream as the socket type and finally we are using TCP/IP so we would
specify protocol type as Tcp.

'Once we have created a Socket we need to make a connection to
the server since we are using connection-based communication. To connect
to the remote computer we need to know the IP Address and port at which
to connect. In .NET there is a class under System.Net namespace called
IPEndPoint which represents a network computer as an IP address and a
port number. The IPEndPoint has two constructors - one that takes a IP
Address and Port number and one that takes long and port number.

Public Sub Connect(ByVal RemoteHostName As String, ByVal
Remoteport As Integer)
Try
Client = New Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)
Port = Remoteport
ipHostInfo = Dns.Resolve(RemoteHostName)
ipAddress = ipHostInfo.AddressList(0)
Dim remoteEP As New IPEndPoint(ipAddress, Port)
Client.BeginConnect(remoteEP, AddressOf sockConnected,
Client)
Catch
RaiseEvent onError(Err.Description)
Exit Sub
End Try

End Sub
#End Region
#Region "Disconnect "
Public Sub Disconnect()
Try
'Kill the socket.
Client.Shutdown(SocketShutdown.Both)
'Kill any data being sent or received.
'let the functions know that we are disconnecting()
'this prevents data being sent after the socket closes
'apparently .Shutdown doesn't work as documented()
'this is the work(around)
mConnected = False
'Kill socket
Client = New Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)
Catch : End Try
End Sub
#End Region
#Region "SockSendEnd "
Private Sub sockSendEnd(ByVal ar As IAsyncResult)
Try
Dim client As Socket = CType(ar.AsyncState, Socket)
Dim bytesSent As Integer = client.EndSend(ar)
RaiseEvent onSendComplete(bytesSent)
Catch
RaiseEvent onError(Err.Description)
Exit Sub
End Try
End Sub
#End Region
#Region " SendData "
Public Sub SendData(ByVal Data() As Byte)
Try
Dim byteData As Byte() = Data
Client.BeginSend(byteData, 0, byteData.Length, 0,
AddressOf sockSendEnd, Client)
Catch
RaiseEvent onError(Err.Description)
Exit Sub
End Try
End Sub
#End Region
#Region "StringToBytes "
Public Function StringToBytes(ByVal Data As String) As Byte()
StringToBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
End Function
#End Region
#Region "BytesToString "
Public Function BytestoString(ByVal Data As Byte()) As String
BytestoString = System.Text.ASCIIEncoding.ASCII.GetString(Data)
End Function
#End Region
#Region "Connected "
Public Function Connected() As Boolean
Try
Return Client.Connected
Catch
RaiseEvent onError(Err.Description)
Exit Function
End Try
End Function
#End Region

End Class

regards



Michael said:
hi!

i'm really not into networking at all and have now been asigned the task of
porting a vb6-code into vb.net (compact framework, in this case) and the
code uses the winsock-control. i quickly found out that .net uses
system.net.sockets.socket or .tcpclient/.tcpserver. and these confuse me...
:blush:| and help would be really great! links, code, wrappers, tips,
whateveryougot...

one of my main problems, i guess, is: why don't sockets raise events like
mysock_gotdata()?! (or like vb6's winsock...) wouldn't that be usefull in
any case? why not have it as part of the framework?

i found sample code where the "receiving" is done in a "while true" loop -
with no exit; except possibly by catching an error, which was done outside
the loop (but i don't think so). wouldn't the program "hang" in it's endless
loop? i found no sign of or any comment on any "multi-threading", but i'm
reallyreally not into that - is it part of the solution?

coming freshly from vb6, vb.net is a joy! with quick and cool results...
...and now this ;o]...

thanks,
m.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top