I an having issuses with a loop I am running to keep checking for
messages coming across our line.
The goal:
Listen for messages on port 5001 and print the messages into a text
file. The port must stay open at all times and only close if no
activity for 60 seconds.
The problem:
If I do a read on a networkstream and the connection is closed
unexpectedly by the client side, the application hangs.
Other usefuldata for reading the sample code:
The networkstream is delimited by a 4 byte header. the first 4 bytes
tell you the length of the data you are reading for a particular
message (in hex)
Any help would be appreciated. Here is some sample code:
Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Sock ets
Imports System.Net.Sock ets.SocketExcep tion
Imports System.Text
Imports Microsoft.Visua lBasic
Imports System.Net.DnsP ermissionAttrib ute
Imports System.Security .Permissions
<DnsPermissionA ttribute(Securi tyAction.Demand , Unrestricted:=T rue)>
Public Class WSGateway
Const portNumber As Integer = 5001
Friend checker As New SocketException ()
Friend tcpListener As New TcpListener(por tNumber)
Public Sub Run()
Const portNumber As Integer = 5001
Dim filecounter As Int32 = 0
Dim tcpListener As New
TcpListener(CTy pe(Dns.Resolve( "Localhost").Ad dressList(0), IPAddress),
portNumber)
Console.WriteLi ne("TCP Server is up and waiting for Client
connection...")
Dim Lifetime As New Sockets.LingerO ption(True, 60)
Try
tcpListener.Sta rt()
While True
Dim tcpClient As TcpClient =
tcpListener.Acc eptTcpClient()
Dim networkStream As NetworkStream =
tcpClient.GetSt ream()
Console.WriteLi ne("Connection accepted.")
Do Until networkStream.D ataAvailable = True
'do nothing
Loop
While networkStream.D ataAvailable
Dim bytes(tcpClient .ReceiveBufferS ize) As Byte
networkStream.R ead(bytes, 0, 4)
filecounter = filecounter + 1
Dim ascii As String =
Replace(Encodin g.ASCII.GetStri ng(bytes), Chr(0), "")
If ascii.Length > 0 Then
Dim x As String =
Integer.Parse(A sc(Trim(ascii)) , Globalization.N umberStyles.Hex Number)
networkStream.R ead(bytes, 0, x - 4)
Dim clientdata As String =
Replace(Encodin g.ASCII.GetStri ng(bytes), Chr(0), "")
Microsoft.Visua lBasic.FileOpen (1, "C:\test" &
filecounter & ".txt", OpenMode.Output , OpenAccess.Writ e,
OpenShare.LockW rite)
Microsoft.Visua lBasic.Print(1, clientdata)
Microsoft.Visua lBasic.FileClos e(1)
Dim responseString As String = ""
responseString = Replace(clientd ata, "POLL
AC", "POLL AC ACK")
Dim resplen As Int32 = responseString. Length +
4
Dim sendBytes As [Byte]() =
Encoding.ASCII. GetBytes(respon seString)
Dim headbytes(4) As Byte
headbytes = Encoding.ASCII. GetBytes(Chr(0) &
Chr(0) & Chr(0) & Chr(resplen))
Dim finalbytes(send Bytes.Length + 4) As Byte
headbytes.CopyT o(finalbytes, 0)
sendBytes.CopyT o(finalbytes, 4)
Microsoft.Visua lBasic.FileOpen (1, "C:\testing "
& filecounter & ".txt", OpenMode.Output , OpenAccess.Writ e,
OpenShare.LockW rite)
Microsoft.Visua lBasic.Print(1,
Encoding.ASCII. GetString(final bytes))
Microsoft.Visua lBasic.FileClos e(1)
networkStream.W rite(finalbytes , 0,
finalbytes.Leng th)
Console.WriteLi ne(("Message Sent by TCP Server
/> : " + responseString) )
If clientdata.Ends With("&H2B") Then
networkStream.C lose()
Exit While
End If
clientdata = ""
responseString = ""
bytes.Clear(byt es, 0, bytes.Length)
Else
networkStream.F lush()
Exit While
End If
End While
End While
tcpListener.Sto p()
Console.WriteLi ne("Exit")
Console.ReadLin e()
Catch e As Exception
Console.WriteLi ne(e.ToString() )
Console.ReadLin e()
End Try
End Sub
End Class 0 1539 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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.
|
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...
|
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...
|
by: Michael Turner |
last post by:
Hi Guys
I have just taken this article from msdn and it is coming up with an error
any ideas why? If any one wants to see where I found it
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconusingudpservices.asp
There error i get is 'Sub Main' is declared more than once in
'ConsoleApplication2': ConsoleApplication2.UDPMulticastListener.Main(),
ConsoleApplication2.UDPMulticastListener.Main(args() As...
|
by: Ben |
last post by:
I modified the logmonitor sdk example so it would work over a network. It
works great when the client and server are running on the same PC and have
administrator privileges. So I have two problems:
1) I cannot run the client without administrator privileges. If I try I get
the following message:
Unhandled Exception: System.Security.SecurityException: Requested registry
access is not allowed.
at...
| |
by: Suresh |
last post by:
Hi Guys
I have Db2 server installed on remote server. i am connecting to that
remote server by using VPN.
I want to connect that remote DB2 server instance using my local
machine DB2 development client. Bur Its gives me following error
message. I searched lots of things on net and tried on remote server
but i didnt got suceess. Can any one tell me how to set TCP\IP
connection protocol on server for particular instance. Becuase I think
|
by: Suresh |
last post by:
Hi Guys
I have Db2 server installed on remote server. i am connecting to that
remote server by using VPN.
I want to connect that remote DB2 server instance using my local
machine DB2 development client. Bur Its gives me following error
message. I searched lots of things on net and tried on remote server
but i didnt got suceess. Can any one tell me how to set TCP\IP
|
by: Mr. Beck |
last post by:
Hello,
Please Help.....
I have been working with some tcp/ip socket communication within a C#
program recently. Basicly, I have a program (myProblemProgram) that has a
socket connected to another program for information passing. Upon receiving
a particular "command" from the the information passing program,
myProblemProgram will launch a separate thread to do individual communication
with another file transfer program. The thread...
|
by: Ryan Liu |
last post by:
Hi,
I have a 100 clients/ one server application, use ugly one thread pre client
approach. And both side user sync I/O.
I frequently see the error on server side(client side code is same, but I
don't see the error):
"System.IO.IOException: Unable to read data from the transport connection:A
blocking operation was interrupted by a call to WSACancelBlockingCall"
|
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...
|
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,...
| |
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...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |