473,805 Members | 2,055 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sockets problem

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.

The WinSock control is not able to fully connect to the vb.net TCPListener.
The winsock.state is
constantly 6 (connecting). Thus I can never send a message to the .net
TCPlistener.

What's interesting is that:
a. I can do the reverse and connect to a vb6 WinSock control from vb.net
TCPClient and communicate without any issues.
b. According to debug information in .net the vb.net TCPListener
establishes a connection with the vb6 winsock control, but in vb6 world the
vb6 control thinks the status is "connecting "

Here is the .net Class that functions as the TCP server:

~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~

Imports System.Net.Sock ets
Imports System.Text
Imports System.Net
Imports Microsoft.Visua lBasic.Strings
Imports ControlChars = Microsoft.Visua lBasic.ControlC hars
Imports PrintMonitor.Da taBaseConnectio n

Public Class SocketServer

' This class will control the WinSock server
' The server will answer client requests, such as request for a list of
project numbers

' default server binding is to the first ethernet interface and port
9900
Private ipAddress As ipAddress =
Dns.Resolve(Dns .GetHostName).A ddressList(0)
Private Const PortNumber As Integer = 9900

' tcp server
Private TCPServer As TcpListener

Private IsListening As Boolean = False
Private PollTimer As New Timer()

' the client that initiates the connection
Private tcpClient As tcpClient
Private tcpSocket As Socket

' networkstream object
Private NetworkStream As NetworkStream

' Client Messages
Private Const ProjectListRequ est As String = "REQUEST:PROJEC T_LIST"
Private Const ExitRequest As String = "EXIT"

'repro database connection
Private db As New PrintMonitor.Da taBaseConnectio n()

Public Sub New()

' initialize the server
Try
TCPServer = New TcpListener(ipA ddress, PortNumber)
Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message)
End Try

'initialize timer
PollTimer.Inter val = 500
PollTimer.Enabl ed = True

AddHandler PollTimer.tick, AddressOf PollTimer_Tick

End Sub

'overloaded
Public Sub New(ByVal ipAddress As ipAddress, ByVal PortNumber As
Integer)

' initialize the server
Try
TCPServer = New TcpListener(ipA ddress, PortNumber)
Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message)
End Try

'initialize timer
PollTimer.Inter val = 500
PollTimer.Enabl ed = True

AddHandler PollTimer.Tick, AddressOf PollTimer_Tick

End Sub

Public Sub startListening( )
Try
TCPServer.Start ()
Console.WriteLi ne("SERVER>list ening on interface " &
ipAddress.ToStr ing & _
" on port " & PortNumber.ToSt ring & ".....")
IsListening = True
Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message)
End Try

' start the timer
PollTimer.Start ()
End Sub

Public Sub stopListening()

If IsListening Then
TCPServer.Stop( )
End If
IsListening = False

End Sub

Private Sub PollTimer_Tick( ByVal sender As Object, ByVal e As
System.EventArg s)

PollTimer.Start ()

' if a conenction is pending, start a new thread and process
connection
If TCPServer.Pendi ng Then

Dim tCheckForConnec tionThread As System.Threadin g.Thread
tCheckForConnec tionThread = New
System.Threadin g.Thread(Addres sOf ProcessConnecti on)
tCheckForConnec tionThread.IsBa ckground = True
tCheckForConnec tionThread.Name = "Checking for Connection <" & _
System.DateTime .Now.ToString & ">"
tCheckForConnec tionThread.Star t()

'CheckForConnec tion()
End If

End Sub

Private Sub ProcessConnecti on()
If TCPServer.Pendi ng Then
Try

tcpSocket = TCPServer.Accep tSocket
Console.WriteLi ne("SERVER>Conn ection accepted.")

' get and convert the message to a string for processing
Dim bReceivedBytes( 1024) As Byte
If tcpSocket.Avail able > bReceivedBytes. Length Then
Console.WriteLi ne("ERROR: Received byte stream larger
than buffer. " & _
"Trancation has occured.")
End If
tcpSocket.Recei ve(bReceivedByt es)

Dim sStreamData As String =
Encoding.ASCII. GetString(bRece ivedBytes)
AnalyzeClientMe ssage(sStreamDa ta)

Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message.ToSt ring)
End Try
End If

'clean up and kill the current thread
If Not IsNothing(tcpSo cket) Then
If tcpSocket.Conne cted Then
Console.WriteLi ne("Closing Connection." )
tcpSocket.Close ()
End If
End If
System.Threadin g.Thread.Curren tThread.Abort()
End Sub

Private Sub AnalyzeClientMe ssage(ByVal MessageText As String)
If InStr(MessageTe xt, ProjectListRequ est) Then
SendProjectList ()
ElseIf InStr(MessageTe xt, ExitRequest) Then
Console.WriteLi ne("SERVER>Exi t command received. Closing
connection.")
Else
Console.WriteLi ne("SERVER>Mess age not understood.")
Console.WriteLi ne("SERVER>Rece ived: " & MessageText &
ControlChars.Cr Lf)
End If

End Sub

Private Sub SendProjectList ()
Console.WriteLi ne("SERVER>Proj ect List was requested")
Dim sprojectlist As String = db.GetProjectLi st
sendMessage("RE SPONSE:PROJECT_ LIST:" & ControlChars.Cr Lf &
sprojectlist)
End Sub

Public Sub sendMessage(ByV al MessageText As String)
Try
If tcpSocket.Conne cted Then
Dim SendBytes(1024) As Byte
SendBytes = Encoding.ASCII. GetBytes(Messag eText)
tcpSocket.Send( SendBytes, SendBytes.Lengt h,
SocketFlags.Non e)
End If
Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message, "Connection Error", _
MessageBoxButto ns.OK, MessageBoxIcon. Error)
End Try
Console.WriteLi ne("SERVER>: " & MessageText)
End Sub
End Class
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~

An object from this class is initialized in a form for now, and the server
is immediately started.

The vb6 winsock control is initialized as in a menu function follows:

~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~

Private Sub mnuInformation_ ProjListUpdate_ Click()
'connect to server and retrieve project list

With frmPopUp.axWins ockClient
.RemoteHost = "192.168.1. 49"
.RemotePort = CLng(9900)
Dim temp As Integer
temp = ServicePointMan ager.DefaultCon nectionLimit
.Connect
Select Case axWinsockClient .State
Case 6
Debug.Print ("connecting... .")
Case 7
Debug.Print ("connected to " & .RemoteHostIP & ":" &
..RemotePort)
End Select
If axWinsockClient .State = 7 Then .SendData ("REQUEST:PROJE CT_LIST")
.Close
End With

End Sub

~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~

Can anyone help me with this?

thanx,

Dmitry


Nov 19 '05 #1
1 7041
Hello everyone,

I finally solved my own problem. I will explain my solution in case someone
is experiencing similar issues.

1. my vb6 application uses some API calls to display a systray icon. Most
of the code is there. while I do not fully understand, the API calls are
somehow preventing the successful connection signal from reaching the
winsock control. I am guessing event messages are being rerouted to one of
the other forms.

2. since most of the tcplistener implementations , including my own, use
either a timer or a thread that sleeps after checking for a connection, you
have to be more careful with commands in vb6. For example, if you use the
SendData command to send that, you have to be sure that the tcplister has
time to receive it, before you issue the .close command from vb6 to close
the connection. you can issue the senddata command, then use the
sendcomplete event to close the connection.

it just takes a little more care to get these two to work together, but
they work quite well.

dmitry
"Dmitry Akselrod" <dm*****@ddi.co m> wrote in message
news:vi******** ****@corp.super news.com...
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.

The WinSock control is not able to fully connect to the vb.net TCPListener. The winsock.state is
constantly 6 (connecting). Thus I can never send a message to the .net
TCPlistener.

What's interesting is that:
a. I can do the reverse and connect to a vb6 WinSock control from vb.net
TCPClient and communicate without any issues.
b. According to debug information in .net the vb.net TCPListener
establishes a connection with the vb6 winsock control, but in vb6 world the vb6 control thinks the status is "connecting "

Here is the .net Class that functions as the TCP server:

~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~

Imports System.Net.Sock ets
Imports System.Text
Imports System.Net
Imports Microsoft.Visua lBasic.Strings
Imports ControlChars = Microsoft.Visua lBasic.ControlC hars
Imports PrintMonitor.Da taBaseConnectio n

Public Class SocketServer

' This class will control the WinSock server
' The server will answer client requests, such as request for a list of project numbers

' default server binding is to the first ethernet interface and port
9900
Private ipAddress As ipAddress =
Dns.Resolve(Dns .GetHostName).A ddressList(0)
Private Const PortNumber As Integer = 9900

' tcp server
Private TCPServer As TcpListener

Private IsListening As Boolean = False
Private PollTimer As New Timer()

' the client that initiates the connection
Private tcpClient As tcpClient
Private tcpSocket As Socket

' networkstream object
Private NetworkStream As NetworkStream

' Client Messages
Private Const ProjectListRequ est As String = "REQUEST:PROJEC T_LIST"
Private Const ExitRequest As String = "EXIT"

'repro database connection
Private db As New PrintMonitor.Da taBaseConnectio n()

Public Sub New()

' initialize the server
Try
TCPServer = New TcpListener(ipA ddress, PortNumber)
Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message)
End Try

'initialize timer
PollTimer.Inter val = 500
PollTimer.Enabl ed = True

AddHandler PollTimer.tick, AddressOf PollTimer_Tick

End Sub

'overloaded
Public Sub New(ByVal ipAddress As ipAddress, ByVal PortNumber As
Integer)

' initialize the server
Try
TCPServer = New TcpListener(ipA ddress, PortNumber)
Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message)
End Try

'initialize timer
PollTimer.Inter val = 500
PollTimer.Enabl ed = True

AddHandler PollTimer.Tick, AddressOf PollTimer_Tick

End Sub

Public Sub startListening( )
Try
TCPServer.Start ()
Console.WriteLi ne("SERVER>list ening on interface " &
ipAddress.ToStr ing & _
" on port " & PortNumber.ToSt ring & ".....")
IsListening = True
Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message)
End Try

' start the timer
PollTimer.Start ()
End Sub

Public Sub stopListening()

If IsListening Then
TCPServer.Stop( )
End If
IsListening = False

End Sub

Private Sub PollTimer_Tick( ByVal sender As Object, ByVal e As
System.EventArg s)

PollTimer.Start ()

' if a conenction is pending, start a new thread and process
connection
If TCPServer.Pendi ng Then

Dim tCheckForConnec tionThread As System.Threadin g.Thread
tCheckForConnec tionThread = New
System.Threadin g.Thread(Addres sOf ProcessConnecti on)
tCheckForConnec tionThread.IsBa ckground = True
tCheckForConnec tionThread.Name = "Checking for Connection <" & _ System.DateTime .Now.ToString & ">"
tCheckForConnec tionThread.Star t()

'CheckForConnec tion()
End If

End Sub

Private Sub ProcessConnecti on()
If TCPServer.Pendi ng Then
Try

tcpSocket = TCPServer.Accep tSocket
Console.WriteLi ne("SERVER>Conn ection accepted.")

' get and convert the message to a string for processing
Dim bReceivedBytes( 1024) As Byte
If tcpSocket.Avail able > bReceivedBytes. Length Then
Console.WriteLi ne("ERROR: Received byte stream larger
than buffer. " & _
"Trancation has occured.")
End If
tcpSocket.Recei ve(bReceivedByt es)

Dim sStreamData As String =
Encoding.ASCII. GetString(bRece ivedBytes)
AnalyzeClientMe ssage(sStreamDa ta)

Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message.ToSt ring)
End Try
End If

'clean up and kill the current thread
If Not IsNothing(tcpSo cket) Then
If tcpSocket.Conne cted Then
Console.WriteLi ne("Closing Connection." )
tcpSocket.Close ()
End If
End If
System.Threadin g.Thread.Curren tThread.Abort()
End Sub

Private Sub AnalyzeClientMe ssage(ByVal MessageText As String)
If InStr(MessageTe xt, ProjectListRequ est) Then
SendProjectList ()
ElseIf InStr(MessageTe xt, ExitRequest) Then
Console.WriteLi ne("SERVER>Exi t command received. Closing
connection.")
Else
Console.WriteLi ne("SERVER>Mess age not understood.")
Console.WriteLi ne("SERVER>Rece ived: " & MessageText &
ControlChars.Cr Lf)
End If

End Sub

Private Sub SendProjectList ()
Console.WriteLi ne("SERVER>Proj ect List was requested")
Dim sprojectlist As String = db.GetProjectLi st
sendMessage("RE SPONSE:PROJECT_ LIST:" & ControlChars.Cr Lf &
sprojectlist)
End Sub

Public Sub sendMessage(ByV al MessageText As String)
Try
If tcpSocket.Conne cted Then
Dim SendBytes(1024) As Byte
SendBytes = Encoding.ASCII. GetBytes(Messag eText)
tcpSocket.Send( SendBytes, SendBytes.Lengt h,
SocketFlags.Non e)
End If
Catch e As System.Net.Sock ets.SocketExcep tion
MessageBox.Show (e.Message, "Connection Error", _
MessageBoxButto ns.OK, MessageBoxIcon. Error)
End Try
Console.WriteLi ne("SERVER>: " & MessageText)
End Sub
End Class
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~

An object from this class is initialized in a form for now, and the server
is immediately started.

The vb6 winsock control is initialized as in a menu function follows:

~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~

Private Sub mnuInformation_ ProjListUpdate_ Click()
'connect to server and retrieve project list

With frmPopUp.axWins ockClient
.RemoteHost = "192.168.1. 49"
.RemotePort = CLng(9900)
Dim temp As Integer
temp = ServicePointMan ager.DefaultCon nectionLimit
.Connect
Select Case axWinsockClient .State
Case 6
Debug.Print ("connecting... .")
Case 7
Debug.Print ("connected to " & .RemoteHostIP & ":" &
.RemotePort)
End Select
If axWinsockClient .State = 7 Then .SendData ("REQUEST:PROJE CT_LIST") .Close
End With

End Sub

~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~

Can anyone help me with this?

thanx,

Dmitry

Nov 19 '05 #2

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

Similar topics

4
15628
by: Dr.Kadzija | last post by:
i have a client-server application. client and server should communicate via tcp sockets. ok, so i use Sockets, PrintWriter and BufferedReader. the problem is that: both client and server will send each other multiple lines (using PrintWriter.println()) at a time, and i don't know how many lines each of them will send. this wouldn't be a problem if a sender could end his turn with a pre-defined character or string (e.g. "\n", "bye" or...
2
3898
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
0
1451
by: Gonçalo Rodrigues | last post by:
Hi, I have a problem with threads and sockets. I'll try to describe the problem in words with pseudo-code. I've been working on a few classes to make it easier to work with threads. This framework, let us call it that, consists in two parts. The first part is just a basic thread class deriving from threading.Thread with a few extra functionality that makes it easier for a thread to spawn a new thread and "father it". Each of its
1
3799
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
1833
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...
14
1874
by: jack | last post by:
At this link I have two c# projects, one is a client, the other is a server. Just point the ip address of the client at the server http://www.slip-angle.com/hosted/bug/ The server does little more than the examples in the c# documentation for how to set up an asynchronous server. It just accepts connections, reads data into a buffer continously, doing nothing with it.
15
2215
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). Unhandled Exception: System.TypeInitializationException: The type...
3
11596
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
5
2254
by: Dan Ritchie | last post by:
I've got a client/server app that I used to send large amounts of data via UDP to the client. We use it in various scenarios, one of which includes rendering a media file on the client as it is transferred via the underlying UDP transport. In this scenario it is very important to keep CPU usage as low as possible. Both the client and server were originally written in C++, but I've re-written the client in C#, partly to simplify it, but...
0
1456
by: rossabri | last post by:
This topic has been addressed in limited detail in other threads: "sockets don't play nice with new style classes :(" May 14 2005. http://groups.google.com/group/comp.lang.python/browse_thread/thread/76d27388b0d286fa/c9849013e37c995b "Subclassing socket" Dec 20 2005 - Jan 14 2006. http://groups.google.com/group/comp.lang.python/browse_thread/thread/391728cd442339c8/c0581b9ee5e7ceaf Briefly, the socket module ("socket.py") provides a...
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
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
10609
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...
1
10366
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
10105
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
5542
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
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4323
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
2
3845
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.