473,770 Members | 2,153 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem With System.Net.Sock ets

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
Nov 21 '05 #1
0 1540

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

Similar topics

1
3795
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
1830
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...
15
2213
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...
2
1999
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...
0
1306
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...
0
3922
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
5
24017
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
1
17551
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...
1
20644
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"
0
9591
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
10228
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
8883
agi2029
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...
0
6676
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
5312
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
5449
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3970
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
3575
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.