473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 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 3743
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
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,...
0
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,...
0
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...

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.