473,915 Members | 5,904 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sockets

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.sock ets.socket or .tcpclient/.tcpserver. and these confuse me...
:o| 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.
Nov 21 '05 #1
3 4379
I'm pretty new at sockets like you but what I found is that some of the
calls (like updclient.recei ve) 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.

"Michael Maercker" <mi**********@i sh.de> wrote in message
news:4251affe@n ews-fe-01...
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.sock ets.socket or .tcpclient/.tcpserver. and these confuse
me...
:o| 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.

Nov 21 '05 #2
sockets do raise event download the sample
http://msdn.microsoft.com/vbasic/dow...s/default.aspx

"Michael Maercker" <mi**********@i sh.de> wrote in message
news:4251affe@n ews-fe-01...
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.sock ets.socket or .tcpclient/.tcpserver. and these confuse
me...
:o| 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.

Nov 21 '05 #3
Option Explicit On
Option Strict Off

Imports System
Imports System.Net
Imports System.Net.Sock ets
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(B yVal Data As Byte(), ByVal
TotalBytes As Integer)
Public Event onDataArrival(B yVal 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("lo calhost")
Private Shared ipAddress As ipAddress = ipHostInfo.Addr essList(0)
Private Shared Client As New Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)
Dim clsReader As New PirateChat.clsR eadWriteXML
Public bConnected As Boolean
Private mConnected As Boolean
#Region "Socketconn ted "
Private Sub sockConnected(B yVal ar As IAsyncResult)
Try
If Client.Connecte d = False Then RaiseEvent
onError("Connec tion refused.") : Exit Sub
Dim state As New StateObject
state.workSocke t = Client
Client.BeginRec eive(state.buff er, 0, state.BufferSiz e,
0, AddressOf sockDataArrival , state)
RaiseEvent onConnect()
Catch
RaiseEvent onError(Err.Des cription)
Exit Sub
End Try
End Sub
#End Region
#Region " DataArrival "

Private Sub sockDataArrival (ByVal ar As IAsyncResult)
Dim state As StateObject = CType(ar.AsyncS tate, StateObject)
Dim client As Socket = state.workSocke t
Dim bytesRead As Integer
' If mConnected = True Then Exit Sub
Try
bytesRead = client.EndRecei ve(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(32 767)

client.BeginRec eive(state.buff er, 0, state.BufferSiz e,
0, AddressOf sockDataArrival , state)
RaiseEvent
onDataArrival(A SCIIEncoding.AS CII.GetString(D ata), bytesRead)
Catch
RaiseEvent onError(Err.Des cription)
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.Sock ets 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(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)
Port = Remoteport
ipHostInfo = Dns.Resolve(Rem oteHostName)
ipAddress = ipHostInfo.Addr essList(0)
Dim remoteEP As New IPEndPoint(ipAd dress, Port)
Client.BeginCon nect(remoteEP, AddressOf sockConnected,
Client)
Catch
RaiseEvent onError(Err.Des cription)
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(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)
Catch : End Try
End Sub
#End Region
#Region "SockSendEn d "
Private Sub sockSendEnd(ByV al ar As IAsyncResult)
Try
Dim client As Socket = CType(ar.AsyncS tate, Socket)
Dim bytesSent As Integer = client.EndSend( ar)
RaiseEvent onSendComplete( bytesSent)
Catch
RaiseEvent onError(Err.Des cription)
Exit Sub
End Try
End Sub
#End Region
#Region " SendData "
Public Sub SendData(ByVal Data() As Byte)
Try
Dim byteData As Byte() = Data
Client.BeginSen d(byteData, 0, byteData.Length , 0,
AddressOf sockSendEnd, Client)
Catch
RaiseEvent onError(Err.Des cription)
Exit Sub
End Try
End Sub
#End Region
#Region "StringToBy tes "
Public Function StringToBytes(B yVal Data As String) As Byte()
StringToBytes = System.Text.ASC IIEncoding.ASCI I.GetBytes(Data )
End Function
#End Region
#Region "BytesToStr ing "
Public Function BytestoString(B yVal Data As Byte()) As String
BytestoString = System.Text.ASC IIEncoding.ASCI I.GetString(Dat a)
End Function
#End Region
#Region "Connected "
Public Function Connected() As Boolean
Try
Return Client.Connecte d
Catch
RaiseEvent onError(Err.Des cription)
Exit Function
End Try
End Function
#End Region

End Class

regards

Michael Maercker wrote:
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.soc kets.socket or .tcpclient/.tcpserver. and these confuse me...
:o| 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.


Nov 21 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3902
by: Tero Saarni | last post by:
Hi, I have several threads communicating with each other using events stored in Queues. Threads block on Queue.get() until somebody publishes an event in thread's event queue. I need to add support for sockets to the system. Thread needs to unblock when: - there is socket ready to be read, or
1
3806
by: Dmitry Akselrod | last post by:
Hello everyone, I have a vb.net application that wraps the TCPListener object in a class. The server connects to the local interface and establishes itself on port 9900. It then polls for pending connections every 500ms. I also have a vb6 application that uses the WinSock control at the other end of the communication tunel. I have to work with vb6 here because it uses less memory than .NET.
0
1853
by: mrpolitics | last post by:
So I'm working with PureIRCD (http://sourceforge.net/projects/pure-ircd) and everything was fine untill yesterday when the server crashed. So I did a cold restart and staretd the server back up now it's throwing this stream of errors right away. Does anyone have any idea what they mean. I havn't changed the source at all since it was working (which was for four days). It errors here saying An unhandled exception of type...
3
10410
by: Logan McKinley | last post by:
I have a C# program that uses blocking sockets and want to allow the user to stop the server. The problem I am having is the socket blocks on -------------------------------------------------------------- listener = new System.Net.Sockets.TcpListener(6254); listener.Start(); //skt is a socket skt =listener.AcceptSocket(); <--- this line blocks -------------------------------------------------------------- I attempt to stop the thread...
1
20441
by: Adam Clauss | last post by:
I am (attempting) to move an existing socket application to use raw sockets. Right now, my application is essentially a port forwarder. Upon receiving a connection, it will open a connection to an "internal" server and simply relay all information back and forth (when the client sends something, my app sends that to the server, when server sends something, my app sends that to the client). While what I have right DOES work, the...
4
6333
by: BadOmen | last post by:
Hi, What is the different between 'System.Net.Sockets.Socket' and 'System.Net.Sockets.TcpClient'? When do I use System.Net.Sockets.TcpClient and System.Net.Sockets.Socket?? Yours, Jonas
3
11605
by: J C | last post by:
Hi, I'm using UDPClient to make a simple DNS server. I notice that intermittently and unpredictibly I get: Unhandled Exception: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.Socket.ReceiveFrom(Byte buffer, Int32 offset, Int32 s
7
6747
by: Adam01 | last post by:
Im using cygwin to test the code of a server I am writing. I've included sys/types.h, sys/socket.h, netdb.h, and arpa/inet.h. And this is the output.. ../../../sockets.cpp: In constructor `network_class::network_class()': ../../../sockets.cpp:64: error: aggregate `addrinfo hints' has incomplete type a nd cannot be defined ../../../sockets.cpp:69: error: `getaddrinfo' undeclared (first use this functio n)
0
9883
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11359
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10928
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11069
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10543
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7259
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5944
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6149
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4779
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.