本文整理汇总了C#中System.Net.Sockets.NetworkStream.EndRead方法的典型用法代码示例。如果您正苦于以下问题:C# NetworkStream.EndRead方法的具体用法?C# NetworkStream.EndRead怎么用?C# NetworkStream.EndRead使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.NetworkStream
的用法示例。
在下文中一共展示了NetworkStream.EndRead方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReadNetworkData
private void ReadNetworkData(NetworkStream stream)
{
try
{
stream.BeginRead(_buffer, 0, _buffer.Length, ar =>
{
ParseBuffer(stream.EndRead(ar));
ReadNetworkData(stream);
}, stream);
}
catch
{
}
}
示例2: Read
private int Read(NetworkStream stream, byte[] buffer, int count)
{
var ar = stream.BeginRead(buffer, 0, count, null, null);
if (!ar.AsyncWaitHandle.WaitOne(SocksTimeout))
{
throw new SocksException("The proxy did not respond in a timely manner.");
}
count = stream.EndRead(ar);
if (count < 2)
{
throw new SocksException("Unable to negotiate with the proxy.");
}
return count;
}
示例3: GetResponse
private static string GetResponse(NetworkStream stream, out string response)
{
byte[] readBuffer = new byte[32];
var asyncReader = stream.BeginRead(readBuffer, 0, readBuffer.Length, null, null);
WaitHandle handle = asyncReader.AsyncWaitHandle;
// Give the reader 2seconds to respond with a value
bool completed = handle.WaitOne(1000, false);
if (completed)
{
int bytesRead = stream.EndRead(asyncReader);
StringBuilder message = new StringBuilder();
message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead));
if (bytesRead == readBuffer.Length)
{
// There's possibly more than 32 bytes to read, so get the next
// section of the response
string continuedResponse;
if (GetResponse(stream, out continuedResponse) != "")
{
message.Append(continuedResponse);
}
}
response = message.ToString();
return response;
}
else
{
int bytesRead = stream.EndRead(asyncReader);
if (bytesRead == 0)
{
// 0 bytes were returned, so the read has finished
response = string.Empty;
return response;
}
else
{
StringBuilder message = new StringBuilder();
message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead));
if (bytesRead == readBuffer.Length)
{
// There's possibly more than 32 bytes to read, so get the next
// section of the response
string continuedResponse;
if (GetResponse(stream, out continuedResponse) != "")
{
message.Append(continuedResponse);
}
}
response = message.ToString();
return response;
}
}
}
示例4: DoLoopInner
protected override EventWaitHandle DoLoopInner(NetworkStream ns, TransferState ts)
{
byte[] bufferread = new byte[1024*1];
byte[] bufferwrite =null;
int count;
ManualResetEvent mreDone = new ManualResetEvent(false);
AsyncCallback readcallback=null;
readcallback = ar_c =>
{
try
{
count = ns.EndRead(ar_c);
ts.AddReadBytes(count);
#if VERBOSE
//if (ts.totalreadbytes % 10000 == 0) ConsoleLogger.LogMessage("read: " + ts.totalreadbytes);
#endif
bool EOFPresent = false;
if (count > 0)
{
EOFPresent = HandleBuffer(bufferread, count, answer, out bufferwrite);
ns.Write(bufferwrite, 0, bufferwrite.Length);
if (bufferwrite != null)
{
ts.AddWriteBytes(bufferwrite.Length);
}
}
if (EOFPresent == false && count>0)
{
ns.BeginRead(bufferread, 0, bufferread.Length, readcallback, ts);
}
else
{
mreDone.Set();
}
}
catch (IOException ioe)
{
if (ioe.InnerException != null)
{
SocketException se = ioe.InnerException as SocketException;
if (se != null)
{
if (se.SocketErrorCode == SocketError.ConnectionReset)
{
ConsoleLogger.LogMessage("Client closed connection!");
mreDone.Set();
return;
}
}
ObjectDisposedException ode = ioe.InnerException as ObjectDisposedException;
if (ode != null)
{
ConsoleLogger.LogMessage("Client closed connection.");
mreDone.Set();
return;
}
}
throw ioe;
}
catch (Exception ex)
{
ConsoleLogger.LogMessage("Error in readcallback: " + ex.ToString());
mreDone.Set();
}
};
//начинаем асинхронное чтение данных
ns.BeginRead(bufferread, 0, bufferread.Length, readcallback, ts);
//ожидаем завершения обработки
mreDone.WaitOne();
//обработка завершена
ConsoleLogger.LogMessage("Thread shutdown!");
return mreDone;
}
示例5: Read
public static Message Read(NetworkStream stream, int timeout)
{
Message message = null;
try
{
//Read length of the message
var lengthBytes = new byte[4];
var asyncResult = stream.BeginRead(lengthBytes, 0, lengthBytes.Length, null, null);
//Wait for result or timeout
asyncResult.AsyncWaitHandle.WaitOne(timeout);
if(asyncResult.IsCompleted)
{
int alreadyRead = stream.EndRead(asyncResult);
message = Read(stream, lengthBytes, alreadyRead);
}
}
catch { }
return message;
}
示例6: Connect
private bool Connect()
{
try
{
TCPClient = new TcpClient(IPAddress, PortNumber);
}
catch (Exception exc)
{
Console.WriteLine("Can't connect: " + exc.Message);
return false;
}
String ConnResult = "";
try
{
TCPStream = TCPClient.GetStream();
byte[] StreamTest = new byte[10];
IAsyncResult NetStreamReadRes = TCPStream.BeginRead(StreamTest, 0, StreamTest.Length, null, null);
if (NetStreamReadRes.AsyncWaitHandle.WaitOne(1500, false))
{
int streamLength = TCPStream.EndRead(NetStreamReadRes);
ConnResult = Encoding.GetEncoding(1251).GetString(StreamTest, 0, streamLength);
}
}
catch (Exception exc)
{
Console.WriteLine("Can't create the network stream: " + exc.Message);
return false;
}
if (ConnResult != "$M$_$ERVER") return false;
SetConnectionStatus(true);
if (Client.User != 0)
{
PackageViaWireless Package = new PackageViaWireless(0, true);
Package.DefineQueryAndParams("ConnectionRecovery", "");
Package.ClientCode = Client.User;
SendPackage(Package.GetPackage());
}
// Запуск пинга сервера
//PingAgent = new CallTimer(PingServer, 500);
return true;
}
示例7: Connect
// # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
private bool Connect()
{
try
{
TCPClient = new TcpClient(IPAddress, PortNumber);
}
catch ( Exception exp )
{
Console.WriteLine("Can't connect: " + exp.Message);
return false;
}
String ConnResult = "";
try
{
TCPStream = TCPClient.GetStream();
byte[] StreamTest = new byte[10];
IAsyncResult NetStreamReadRes = TCPStream.BeginRead(StreamTest, 0, StreamTest.Length, null, null);
if ( NetStreamReadRes.AsyncWaitHandle.WaitOne(3000, false) )
{
int streamLength = TCPStream.EndRead(NetStreamReadRes);
NetStreamReadRes = null;
ConnResult = Encoding.GetEncoding(1251).GetString(StreamTest, 0, streamLength);
}
else
{
System.Diagnostics.Trace.WriteLine("Не получил ответа о сервере");
}
}
catch ( Exception exp )
{
Console.WriteLine("Can't create the network stream: " + exp.Message);
return false;
}
if ( ConnResult != "$M$_$ERVER" ) return false;
SetConnectionStatus(true);
// Запуск пинга сервера
//PingAgent = new CallTimer(PingServer, 500);
Console.WriteLine("Соединение установлено");
return true;
}
示例8: ReceiveDataAndEnqueue
internal void ReceiveDataAndEnqueue()
{
log.Context = MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name;
log.WriteLog("Received Data and Enqueue thread started");
string s;
int iCRat, iCRcount;
string[] sa;
int length = 0;
string sLastErrorMessage = "";
while (!m_bDone)
{
if (m_ConnectionErrorOccurred)
{
continue;
}
try
{
try
{
m_TCPClient.ReceiveTimeout = 100;
m_NetworkStream = m_TCPClient.GetStream();
// m_NetworkStream.Read(m_bytesIncomingBuffer,m_iBufferLength,m_iBufferMaxLength - m_iBufferLength);
IAsyncResult asr = m_NetworkStream.BeginRead(m_bytesIncomingBuffer, m_iBufferLength, m_iBufferMaxLength -
m_iBufferLength, null, null);
while (!asr.IsCompleted && !m_bDone)
{
Thread.Sleep(100);
}
if (m_bDone)
{
continue;
}
length = m_NetworkStream.EndRead(asr);
}
catch (IOException ioex)
{
if (null != ioex.InnerException)
{
if (ioex.InnerException is SocketException)
{
int iErrorCode = ((SocketException) ioex.InnerException).ErrorCode;
// if (iErrorCode == 10060)
// { // read timeout... just continue
// //TODO: This doesn't work in .NET 2.0!!! Must change implementation!
// continue;
// }
string sErrorMessage = ioex.InnerException.Message;
sLastErrorMessage = "ReceiveDataAndEnqueue: Error Code = " + iErrorCode.ToString() + " Description = " +
sErrorMessage;
}
else
{
sLastErrorMessage = "ReceiveDataAndEnqueue: Unknown Error detected. Description = " + ioex.Message;
}
}
log.WriteLog(sLastErrorMessage);
m_bDone = true;
m_bConnected = false;
}
catch (Exception ex)
{
sLastErrorMessage = "ReceiveDataAndEnqueue: Unknown Error detected. Description = " + ex.Message;
log.WriteLog(sLastErrorMessage);
m_bDone = true;
m_bConnected = false;
}
if (!m_bConnected)
{
OnConnectionErrorReceived(this, sLastErrorMessage);
continue;
}
if (m_bDone)
continue;
if (0 == length)
{
// connection must have been reset
m_bDone = true;
continue;
}
m_iBufferLength += length;
// find all the messages in the stream
iCRcount = 0;
for (int i = 0; i < m_iBufferLength; i++)
{
if (m_bytesIncomingBuffer[i] == 13)
iCRcount++;
} // for
// post all messages from the stream
for (int i = 0; i < iCRcount; i++)
{
s = Encoding.ASCII.GetString(m_bytesIncomingBuffer);
s = s.Substring(0, m_iBufferLength);
iCRat = s.IndexOf((char) 13);
if (-1 != iCRat)
{
int iLen;
//.........这里部分代码省略.........
示例9: ReadCallback
private void ReadCallback(IAsyncResult result)
{
int length = 0;
try
{
_stream = _client.GetStream();
if (_stream != null)
length = _stream.EndRead(result);
}
catch
{
Log.Error("Lost connection from loginserver");
return;
}
if (length == 0)
{
return;
}
byte[] data = new byte[length];
Buffer.BlockCopy(_buffer, 0, data, 0, length);
HandlePacket(data);
_stream.BeginRead(_buffer, 0, _buffer.Length, ReadCallback, _buffer);
}