472,990 Members | 3,684 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,990 software developers and data experts.

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.Sockets
Imports System.Text
Imports System.Net
Imports Microsoft.VisualBasic.Strings
Imports ControlChars = Microsoft.VisualBasic.ControlChars
Imports PrintMonitor.DataBaseConnection

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).AddressList(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 ProjectListRequest As String = "REQUEST:PROJECT_LIST"
Private Const ExitRequest As String = "EXIT"

'repro database connection
Private db As New PrintMonitor.DataBaseConnection()

Public Sub New()

' initialize the server
Try
TCPServer = New TcpListener(ipAddress, PortNumber)
Catch e As System.Net.Sockets.SocketException
MessageBox.Show(e.Message)
End Try

'initialize timer
PollTimer.Interval = 500
PollTimer.Enabled = 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(ipAddress, PortNumber)
Catch e As System.Net.Sockets.SocketException
MessageBox.Show(e.Message)
End Try

'initialize timer
PollTimer.Interval = 500
PollTimer.Enabled = True

AddHandler PollTimer.Tick, AddressOf PollTimer_Tick

End Sub

Public Sub startListening()
Try
TCPServer.Start()
Console.WriteLine("SERVER>listening on interface " &
ipAddress.ToString & _
" on port " & PortNumber.ToString & ".....")
IsListening = True
Catch e As System.Net.Sockets.SocketException
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.EventArgs)

PollTimer.Start()

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

Dim tCheckForConnectionThread As System.Threading.Thread
tCheckForConnectionThread = New
System.Threading.Thread(AddressOf ProcessConnection)
tCheckForConnectionThread.IsBackground = True
tCheckForConnectionThread.Name = "Checking for Connection <" & _
System.DateTime.Now.ToString & ">"
tCheckForConnectionThread.Start()

'CheckForConnection()
End If

End Sub

Private Sub ProcessConnection()
If TCPServer.Pending Then
Try

tcpSocket = TCPServer.AcceptSocket
Console.WriteLine("SERVER>Connection accepted.")

' get and convert the message to a string for processing
Dim bReceivedBytes(1024) As Byte
If tcpSocket.Available > bReceivedBytes.Length Then
Console.WriteLine("ERROR: Received byte stream larger
than buffer. " & _
"Trancation has occured.")
End If
tcpSocket.Receive(bReceivedBytes)

Dim sStreamData As String =
Encoding.ASCII.GetString(bReceivedBytes)
AnalyzeClientMessage(sStreamData)

Catch e As System.Net.Sockets.SocketException
MessageBox.Show(e.Message.ToString)
End Try
End If

'clean up and kill the current thread
If Not IsNothing(tcpSocket) Then
If tcpSocket.Connected Then
Console.WriteLine("Closing Connection." )
tcpSocket.Close()
End If
End If
System.Threading.Thread.CurrentThread.Abort()
End Sub

Private Sub AnalyzeClientMessage(ByVal MessageText As String)
If InStr(MessageText, ProjectListRequest) Then
SendProjectList()
ElseIf InStr(MessageText, ExitRequest) Then
Console.WriteLine("SERVER>Exit command received. Closing
connection.")
Else
Console.WriteLine("SERVER>Message not understood.")
Console.WriteLine("SERVER>Received: " & MessageText &
ControlChars.CrLf)
End If

End Sub

Private Sub SendProjectList()
Console.WriteLine("SERVER>Project List was requested")
Dim sprojectlist As String = db.GetProjectList
sendMessage("RESPONSE:PROJECT_LIST:" & ControlChars.CrLf &
sprojectlist)
End Sub

Public Sub sendMessage(ByVal MessageText As String)
Try
If tcpSocket.Connected Then
Dim SendBytes(1024) As Byte
SendBytes = Encoding.ASCII.GetBytes(MessageText)
tcpSocket.Send(SendBytes, SendBytes.Length,
SocketFlags.None)
End If
Catch e As System.Net.Sockets.SocketException
MessageBox.Show(e.Message, "Connection Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Console.WriteLine("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.axWinsockClient
.RemoteHost = "192.168.1.49"
.RemotePort = CLng(9900)
Dim temp As Integer
temp = ServicePointManager.DefaultConnectionLimit
.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:PROJECT_LIST")
.Close
End With

End Sub

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

Can anyone help me with this?

thanx,

Dmitry


Jul 19 '05 #1
1 3684
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.com> wrote in message
news:vi************@corp.supernews.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.Sockets
Imports System.Text
Imports System.Net
Imports Microsoft.VisualBasic.Strings
Imports ControlChars = Microsoft.VisualBasic.ControlChars
Imports PrintMonitor.DataBaseConnection

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).AddressList(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 ProjectListRequest As String = "REQUEST:PROJECT_LIST"
Private Const ExitRequest As String = "EXIT"

'repro database connection
Private db As New PrintMonitor.DataBaseConnection()

Public Sub New()

' initialize the server
Try
TCPServer = New TcpListener(ipAddress, PortNumber)
Catch e As System.Net.Sockets.SocketException
MessageBox.Show(e.Message)
End Try

'initialize timer
PollTimer.Interval = 500
PollTimer.Enabled = 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(ipAddress, PortNumber)
Catch e As System.Net.Sockets.SocketException
MessageBox.Show(e.Message)
End Try

'initialize timer
PollTimer.Interval = 500
PollTimer.Enabled = True

AddHandler PollTimer.Tick, AddressOf PollTimer_Tick

End Sub

Public Sub startListening()
Try
TCPServer.Start()
Console.WriteLine("SERVER>listening on interface " &
ipAddress.ToString & _
" on port " & PortNumber.ToString & ".....")
IsListening = True
Catch e As System.Net.Sockets.SocketException
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.EventArgs)

PollTimer.Start()

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

Dim tCheckForConnectionThread As System.Threading.Thread
tCheckForConnectionThread = New
System.Threading.Thread(AddressOf ProcessConnection)
tCheckForConnectionThread.IsBackground = True
tCheckForConnectionThread.Name = "Checking for Connection <" & _ System.DateTime.Now.ToString & ">"
tCheckForConnectionThread.Start()

'CheckForConnection()
End If

End Sub

Private Sub ProcessConnection()
If TCPServer.Pending Then
Try

tcpSocket = TCPServer.AcceptSocket
Console.WriteLine("SERVER>Connection accepted.")

' get and convert the message to a string for processing
Dim bReceivedBytes(1024) As Byte
If tcpSocket.Available > bReceivedBytes.Length Then
Console.WriteLine("ERROR: Received byte stream larger
than buffer. " & _
"Trancation has occured.")
End If
tcpSocket.Receive(bReceivedBytes)

Dim sStreamData As String =
Encoding.ASCII.GetString(bReceivedBytes)
AnalyzeClientMessage(sStreamData)

Catch e As System.Net.Sockets.SocketException
MessageBox.Show(e.Message.ToString)
End Try
End If

'clean up and kill the current thread
If Not IsNothing(tcpSocket) Then
If tcpSocket.Connected Then
Console.WriteLine("Closing Connection." )
tcpSocket.Close()
End If
End If
System.Threading.Thread.CurrentThread.Abort()
End Sub

Private Sub AnalyzeClientMessage(ByVal MessageText As String)
If InStr(MessageText, ProjectListRequest) Then
SendProjectList()
ElseIf InStr(MessageText, ExitRequest) Then
Console.WriteLine("SERVER>Exit command received. Closing
connection.")
Else
Console.WriteLine("SERVER>Message not understood.")
Console.WriteLine("SERVER>Received: " & MessageText &
ControlChars.CrLf)
End If

End Sub

Private Sub SendProjectList()
Console.WriteLine("SERVER>Project List was requested")
Dim sprojectlist As String = db.GetProjectList
sendMessage("RESPONSE:PROJECT_LIST:" & ControlChars.CrLf &
sprojectlist)
End Sub

Public Sub sendMessage(ByVal MessageText As String)
Try
If tcpSocket.Connected Then
Dim SendBytes(1024) As Byte
SendBytes = Encoding.ASCII.GetBytes(MessageText)
tcpSocket.Send(SendBytes, SendBytes.Length,
SocketFlags.None)
End If
Catch e As System.Net.Sockets.SocketException
MessageBox.Show(e.Message, "Connection Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Console.WriteLine("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.axWinsockClient
.RemoteHost = "192.168.1.49"
.RemotePort = CLng(9900)
Dim temp As Integer
temp = ServicePointManager.DefaultConnectionLimit
.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:PROJECT_LIST") .Close
End With

End Sub

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

Can anyone help me with this?

thanx,

Dmitry

Jul 19 '05 #2

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

Similar topics

4
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...
2
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...
0
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...
14
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...
1
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...
15
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...
3
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...
5
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...
0
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....
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.