|
Hello. I have a problem while reading bytes from a socket.
According to my test, it seems that the buffer maximum size is 8192 bytes. Then, I use a byte array with that size to read from the buffer. If the send data size is 8192 or less, it works ok.
But, if I send more that 8192, let's say 10000 bytes, the first time I read from the buffer I get 8192, and the second, instead of 1808 bytes, it reads 8192 again!!!
Isn't the buffer emptied after the reading?
Regards,
Diego F.
|
|
|
|
|
Are you sure of the number of bytes? Maybe you are miscalculating or your call that reads the stream does not move the position to the remaining bytes.
Maybe if you can post the code in your loop, we can see what is wrong.
-----
Formerly MP(2)
If atheism is a religion, then not collecting stamps is a hobby. -- Unknown
|
|
|
|
|
I send here the code I'm using to test that problem. If I send messages that have a length less that 8192, it works ok. I control the length of the string with the data and the length is what expected.
But, if sent data are over 8192, the second time the code enters the loop, the string with result data has 8192 again.
This is the client code:
Dim bytes_recibidos(8192) As Byte
Dim datos_recibidos As String
Dim p As New IPEndPoint(IPAddress.Parse("127.0.0.1"), 870)
sock = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Try
sock.Connect(p)
ListBox1.Items.Add("Conectado")
Dim socket_conectado As Boolean = True
While (socket_conectado)
If (sock.Poll(0, SelectMode.SelectRead) And (sock.Available = 0)) Then
socket_conectado = False
End If
sock.Receive(bytes_recibidos)
datos_recibidos = (System.Text.Encoding.ASCII.GetString(bytes_recibidos)).TrimEnd(Chr(0))
...
End While
Catch ex As Exception
End Try
And the server code to test that problem:
Dim server As TcpListener
server = Nothing
Try
server = New TcpListener(IPAddress.Parse("127.0.0.1"), 870)
ListBox1.Items.Add("Esperando conexiones...")
server.Start()
Dim cliente As TcpClient = server.AcceptTcpClient()
Dim stream As NetworkStream = cliente.GetStream()
Dim bytes_enviados(8192) As Byte
For i As Integer = 1 To 106
Dim cmd As String = Chr(0) & "12345678901234567890123456789012345678901234567890412345678901234567890123465"
bytes_enviados = System.Text.Encoding.ASCII.GetBytes(cmd)
stream.Write(bytes_enviados, 0, bytes_enviados.Length)
Next
Catch ex As SocketException
Finally
server.Stop()
End Try
Regards,
Diego F.
|
|
|
|
|
Hi Diego,
First off, this is a C# forum. It is not that I want to be picky, but I hate looking at VB.NET code, it gives me rash.
Second, your socket reading code is not familiar to me, but this is not the kind of code I would be using. Use a while this way instead:
int nbBytesRead;
while ((nbBytesRead = sock.Receive(bytes_recibidos)) > 0)
{
datos_recibidos = (System.Text.Encoding.ASCII.GetString(bytes_recibidos)).TrimEnd(Chr(0))
....
}
I don't recommend using the Socket.Poll method in a loop. Use it once before the loop, if you want to see if there is data available. Also, you don't need to check for the Socket.Available method, since if Poll returns true , there is data available to read.
I don't know what your application does, but if you expect the server to return data immediately after connecting to it, there is no need to Socket.Poll your client socket. Just use the Socket.Receive, which blocks until data is available. If in your application you don't want to wait undefinetely for data, use the following code after creating your socket:
sock.ReceiveTimeout = 10000;
Good luck.
-----
Formerly MP(2)
If atheism is a religion, then not collecting stamps is a hobby. -- Unknown
|
|
|
|
|
The reason why you always get 8192 bytes is because you don't use the number of bytes returned by the call to Socket.Receive.
In my other post, replace the following statement:
datos_recibidos = (System.Text.Encoding.ASCII.GetString(bytes_recibidos)).TrimEnd(Chr(0));
with:
datos_recibidos = (System.Text.Encoding.ASCII.GetString(bytes_recibidos, 0, nbBytesRead)).TrimEnd(Chr(0));
I cannot see the complete code from your while , but in the loop that does not have the complete number of bytes (10000 minus 8192), the call only overwrites the first 1808 bytes in your array, leaving the rest with bytes from the previous read loop.
The Encoding.GetBytes method does not copy the string terminating character (\0) in the array of bytes on the server side.
-----
Formerly MP(2)
If atheism is a religion, then not collecting stamps is a hobby. -- Unknown
|
|
|
|
|
Ok, I did change it. Thank you for your advise.
Regards,
Diego F.
|
|
|
|
|
First of all, my excuses for posting here. This should be in VB.NET subforum.
Anyway, I found the mistake. When I do sock.Receive, the array isn't cleared. I didn't expected that, but if I read 100 bytes and the time before it was 150 bytes, the last 50 bytes are from the first time.
So I used the Array.Clear method and I avoid that problem.
Regards,
Diego F.
|
|
|
|
|
Diego, it is not the right way to do it. Use the value returned by Socket.Receive to know how many bytes are read. Read my 2 other replies to your post (the one you show the code used).
-----
Formerly MP(2)
If atheism is a religion, then not collecting stamps is a hobby. -- Unknown
|
|
|
|
|
Hy does anyone know a good programm to generate a UML diagram out of C# code?
|
|
|
|
|
Star UML[^] has reverse engineering from C# code to UML.
|
|
|
|
|
Hi guys , just wondering if anyone knows much about global mouse hooks in c#. I ve basically used this tutorial to implement a simple hook that can grab mouse clicks and x & y.
http://www.codeproject.com/csharp/globalhook.asp[^]
I now have a requirement where I need to specifically get the name or text associated with the item ive clicked on. IE if I clicked on the 'File' menu in wordXP id like to be able to get the word 'File' and store it in a variable for future use.
Iam pretty sure this task is going to involve monitoring windows messages but iam not really sure where to start. does anybody have any experience in this area?
Thanks Mike
|
|
|
|
|
I have an C# ASP.NET web page. I have this conversion problem with my string array to my session variable.
string[] stModArray = (string[])Session["modArray"];
Any suggestions...... Thanks in advance!!
Michael
|
|
|
|
|
Hello,
As the Session["modArray"] is only returning a string or null you can not cast it directly to string[].
You would have to create an string[] instance and add the result string to the array (at the index you would like it to be).
To make it dynamic, you caould use a System.Collections.Specialized.StringCollection (with the "add" method) instead of string[].
P.S.: allways make a !=null check.
Hope it helps!
All the best,
Martin
|
|
|
|
|
Do this:
object o = Session["modArray"];
and check in the debugger to see what's actually stored there. If it's not a string[], you can't turn it into one, at least not like this.
Christian Graus - Microsoft MVP - C++
Metal Musings - Rex and my new metal blog
"I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
|
|
|
|
|
Ok, what I have in this variable are three primary key numbers, so what's getting stored is an int. But the reason why I'm using a string is because I need to return the length for my for loop so the user can cycle backwards and forward viewing each record.
-> There are no nulls getting passed in, what's getting passed in is correct.
This is the snippart of the code that I'm using to try and do what I've just explaned. Once again since I'm I using a loop, objects and such don't have the length function :'(
private void nextMod()
{
string[] stModArray = (string[])Session["modArray"];
for (int i=0; i
|
|
|
|
|
Hi,
Does anyone know how to show and hide a layer in a Visio shape in c#.NET.
Thanks!
|
|
|
|
|
Hi,
I have some custom controls and all have methods BeginInit() and EndInit() in it.
In most cases both methods are empty and probably will always empty.
Is there any performance problem, because I notice in myForm.designer all controls have this two lines:
((System.ComponentModel.ISupportInitialize)(this.crLabel20)).BeginInit();
(System.ComponentModel.ISupportInitialize)(this.crLabe20)).EndInit();
I suppose for all controls both methods are called at runtime. Is this performance wasteful?
Thanks and sorry my english,
Jure
|
|
|
|
|
Hello,
Tavbi wrote: I suppose for all controls both methods are called at runtime.
Yes, it will be called from the constructor (InitialzeComponets) of your form. (When you initialize your form)
Tavbi wrote: Is this performance wasteful?
No!
I wouldn't care too much about it.
But maybe if you don't need it at all, you should think of removing it, just to make the code simpler.
All the best,
Martin
|
|
|
|
|
|
|
Err but it looks like these were generated by VS. I wouldn't touch them.
"Throughout human history, we have been dependent on machines to survive. Fate, it seems, is not without a sense of irony. " - Morpheus
"Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe
|
|
|
|
|
No, No, No!
What I mean is removing the interface from the Custom controls (labels,...)
Hope he understood it.
|
|
|
|
|
Since that's deigned generated code, the changes you make in there will be overwritten the next time the designed refreshes it. You can also break the designer by messing with that code too!
|
|
|
|
|
No, No, No!
What I mean is removing the interface from the Custom controls (labels,...)
Hope he understood it.
|
|
|
|
|
Error
------------
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
-------------
i try to use this code
but i have error
***************
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create("https://isp.paltel.net/login.cfm");
// If required by the server, set the credentials.
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
Console.Read();
}
}
}
***************
Palestine
|
|
|
|