本文整理汇总了C#中System.Net.Sockets.NetworkStream.ReadAsync方法的典型用法代码示例。如果您正苦于以下问题:C# NetworkStream.ReadAsync方法的具体用法?C# NetworkStream.ReadAsync怎么用?C# NetworkStream.ReadAsync使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Sockets.NetworkStream
的用法示例。
在下文中一共展示了NetworkStream.ReadAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Ping
public async Task<PingPayload> Ping(){
NetworkStream = null;
WriteBuffer.Clear();
ReadOffset = 0;
var client = new TcpClient();
await client.ConnectAsync(Host, Port);
if (!client.Connected)
return null;
NetworkStream = client.GetStream();
/*
* Send a "Handshake" packet
* http://wiki.vg/Server_List_Ping#Ping_Process
*/
WriteVarInt(47);
WriteString(Host);
WriteShort(Port);
WriteVarInt(1);
await Flush(0);
/*
* Send a "Status Request" packet
* http://wiki.vg/Server_List_Ping#Ping_Process
*/
await Flush(0);
var message = new List<byte>();
var buf = new byte[1024];
var bytes = await NetworkStream.ReadAsync(buf, 0, buf.Length, CancellationToken);
message.AddRange(new ArraySegment<byte>(buf, 0, bytes));
var length = ReadVarInt(buf);
var left = length - (message.Count - ReadOffset);
while (left > 0) {
buf = new byte[1024];
bytes = await NetworkStream.ReadAsync(buf, 0, buf.Length, CancellationToken);
message.AddRange(new ArraySegment<byte>(buf, 0, bytes));
left -= bytes;
}
client.Close();
ReadOffset = 0;
var buffer = message.ToArray();
length = ReadVarInt(buffer);
ReadVarInt(buffer); // packetID
var jsonLength = ReadVarInt(buffer);
var json = ReadString(buffer, jsonLength);
var ping = JsonConvert.DeserializeObject<PingPayload>(json);
ping.Motd = ping.Motd != null ? CleanMotd(ping.Motd) : null;
return ping;
}
示例2: ConvertStream
/// <summary>
/// input stream에 있는 문자열을 output stream에 맞도록 변환하여 전달한다
/// 만약 stream이 연결이 끊켰을 경우 false를 반환한다
/// 에러가 난 경우 무시한다.
/// </summary>
/// <param name="input"></param>
/// <param name="output"></param>
/// <param name="input_codepage"></param>
/// <param name="output_codepage"></param>
/// <returns></returns>
protected async Task<bool> ConvertStream(NetworkStream input, NetworkStream output, int input_codepage, int output_codepage)
{
byte[] buf = new byte[8196];
int read_bytes = await input.ReadAsync(buf, 0, 8196);
if (read_bytes == 0)
{
return false;
}
try
{
string converted_string = Encoding.GetEncoding(input_codepage).GetString(buf, 0, read_bytes);
byte[] converted_buf = Encoding.GetEncoding(output_codepage).GetBytes(converted_string);
await output.WriteAsync(converted_buf, 0, converted_buf.Count());
}
catch (Exception e)
{
// 인코딩 변환 실패는 에러만 출력하고 그냥 무시한다.
Console.WriteLine("ConvertStream Fail: " + e.Message);
return true;
}
return true;
}
示例3: buttonConnect_Click
private async void buttonConnect_Click(object sender, RibbonControlEventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxIp.Text))
{
try {
if (listner != null)
{
listner.Stop();
listner = null;
}
listner = new TcpListener(IPAddress.Parse(comboBoxIp.Text),port);
listner.Start();
labelStatus.Label = "データ待機中";
client = await listner.AcceptTcpClientAsync();
stream = client.GetStream();
byte[] buff = new byte[1];
var read = await stream.ReadAsync(buff, 0, buff.Length);
ExecuteCommand(buff[0]);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("IPを選択してください");
}
}
示例4: AuthenticateV5
private async Task AuthenticateV5(NetworkStream stream, CancellationToken cancellationToken)
{
await stream.WriteAsync(new byte[] { 5, 2, 0, 2 }, 0, 4, cancellationToken);
switch ((await ReadBytes(stream, 2, cancellationToken)).Last())
{
case 0:
break;
case 2:
await stream.WriteAsync(new byte[] { 1, 0, 0 }, 0, 3, cancellationToken);
byte[] buffer = new byte[2];
int received = 0;
while (received != 2)
{
received += await stream.ReadAsync(buffer, received, 2 - received, cancellationToken);
}
if (buffer[1] != 0)
{
throw new SocksRequestFailedException("Authentication failed");
}
break;
case 255:
throw new SocksRequestFailedException("No authentication method accepted.");
default:
throw new SocksRequestFailedException();
}
}
示例5: ReadAsync
private async void ReadAsync(NetworkStream stream)
{
byte[] buffer = new byte[100];
while (true)
{
try
{
int length = await stream.ReadAsync(buffer, 0, buffer.Length);
Invoke(new MethodInvoker(delegate
{
outputText.Append(buffer, length);
}));
}
catch
{
if (this.Visible)
{ // we're not being closed
Invoke(new MethodInvoker(delegate
{
Stop();
}));
}
break;
}
}
}
示例6:
// read memory buffer helper
async static Task<byte[]>ReadMessage(NetworkStream s)
{
MemoryStream ms = new System.IO.MemoryStream();
byte[] buffer = new byte[0x1000];
do { ms.Write(buffer, 0, await s.ReadAsync(buffer, 0, buffer.Length)); }
while (s.DataAvailable);
return ms.ToArray();
}
示例7: RecvMsg
// Receive a message synchronously
public static async Task<object> RecvMsg(NetworkStream stream)
{
byte[] lenbuf = new byte[MSG_HDR_SIZE];
// receive message length
int bytesRead = await stream.ReadAsync(lenbuf, 0, lenbuf.Length);
if (bytesRead != MSG_HDR_SIZE)
throw new ApplicationException(String.Format("RecvMessage: unexpected message length size with {0} bytes", bytesRead));
// receive message payload
return await RecvMsg(stream, lenbuf);
}
示例8: ConnectAsync
/// <summary>
/// Connect to the EV3 brick.
/// </summary>
/// <returns></returns>
public async Task ConnectAsync()
{
_client = new TcpClient();
await _client.ConnectAsync(_address, 5555);
_stream = _client.GetStream();
// unlock the brick (doesn't actually need serial number?)
byte[] buff = Encoding.UTF8.GetBytes(UnlockCommand);
await _stream.WriteAsync(buff, 0, buff.Length);
// read the "Accept:EV340\r\n\r\n" response
int read = await _stream.ReadAsync(buff, 0, buff.Length);
string response = Encoding.UTF8.GetString(buff, 0, read);
if(string.IsNullOrEmpty(response))
throw new Exception("LEGO EV3 brick did not respond to the unlock command.");
_tokenSource = new CancellationTokenSource();
Task t = Task.Factory.StartNew(async () =>
{
while(!_tokenSource.IsCancellationRequested)
{
// if the stream is valid and ready
if(_stream != null && _stream.CanRead)
{
await _stream.ReadAsync(_sizeBuffer, 0, _sizeBuffer.Length);
short size = (short)(_sizeBuffer[0] | _sizeBuffer[1] << 8);
if(size == 0)
return;
byte[] report = new byte[size];
await _stream.ReadAsync(report, 0, report.Length);
if (ReportReceived != null)
ReportReceived(this, new ReportReceivedEventArgs { Report = report });
}
}
}, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
}
示例9: Run
public static void Run()
{
var socket = SocketBuilder.GetSocket();
var networkStream = new NetworkStream(socket);
var buffer = new byte[0x1000];
// begin
var task = networkStream.ReadAsync(buffer, 0, 1);
// end
task.Wait();
Logger.Log("Byte: {0}", buffer[0]);
}
示例10: ReadRequest
private async Task<String> ReadRequest(NetworkStream stream)
{
var encoding = Encoding.UTF8;
var i = 0;
var bytes = new byte[1024];
var sb = new StringBuilder();
while ((i = await stream.ReadAsync(bytes, 0, bytes.Length)) != 0)
{
sb.Append(encoding.GetString(bytes, 0, i));
if (!stream.DataAvailable) break;
}
return sb.ToString();
}
示例11: GetRawRequestAsync
public async Task<byte[]> GetRawRequestAsync(NetworkStream stream)
{
Requires.NotNull(stream, "stream");
if (!stream.CanRead)
{
throw new IOException();
}
var buffer = new byte[DefaultBufferSize];
using (var memoryStream = new MemoryStream(DefaultBufferSize))
{
while (stream.DataAvailable)
{
int read = await stream.ReadAsync(buffer, 0, buffer.Length);
// resize a raw request array
await memoryStream.WriteAsync(buffer, 0, read);
}
return memoryStream.ToArray();
}
}
示例12: ClientReceive
public async Task<ServerClientMsg> ClientReceive(NetworkStream networkStream)
{
var ReadBytes = new byte[8192];
ServerClientMsg ReceivedObject = new ServerClientMsg();
int BytesRead = await networkStream.ReadAsync(ReadBytes, 0, ReadBytes.Length);
if (BytesRead > 0)
{
ClientSb.Append(Encoding.UTF8.GetString(ReadBytes, 0, BytesRead));
var ReceivedMsg = ClientSb.ToString();
if (ReceivedMsg.IndexOf("</TcpMsg>") > -1)
{
XmlSerializer xmlS = new XmlSerializer(typeof(ServerClientMsg));
using (var stringReader = new StringReader(ReceivedMsg))
{
ReceivedObject = (ServerClientMsg)xmlS.Deserialize(stringReader);
}
ClientSb.Clear();
}
}
return ReceivedObject;
}
示例13: readFromNetworkStreamAsync
//public void readFromNetworkStream(TcpClient client, NetworkStream stream)
//{
// discardProcessedData();
// //read if there's something to read and if we have available storage
// do
// {
// //CJobDispatcher.checkConnection(client);
// if (stream.DataAvailable && m_bytesInBuffer < m_maxChunkSize)
// {
// m_bytesInBuffer += stream.Read(m_buffer, m_bytesInBuffer, m_maxChunkSize - m_bytesInBuffer);
// }
// if (m_bytesInBuffer == 0) Thread.Sleep(200);
// } while (m_bytesInBuffer == 0);
//}
public async Task<int> readFromNetworkStreamAsync(TcpClient client, NetworkStream stream,CancellationToken cancelToken)
{
int numBytesRead= 0;
discardProcessedData();
//read if there's something to read and if we have available storage
try { numBytesRead = await stream.ReadAsync(m_buffer, m_bytesInBuffer, m_maxChunkSize - m_bytesInBuffer, cancelToken); }
catch (OperationCanceledException) { logMessage("async read from network stream cancelled"); }
m_bytesInBuffer += numBytesRead;
return numBytesRead;
}
示例14: ReceiveAsync
protected async Task<byte[]> ReceiveAsync(NetworkStream stream)
{
try
{
int len = await stream.ReadAsync(_receiveBuffer, 0, _receiveBuffer.Length);
stream.Flush();
// 异步接收回答
if (len > 0)
{
return CheckReplyDatagram(len);
}
return null;
}
catch (Exception err)
{
AddInfo("receive exception: " + err.Message);
CloseClientSocket();
return null;
}
}
示例15: ReadWithTimeout
/// <summary>
/// Reads from the stream with provided timeout
/// </summary>
/// <param name="stream">The stream to read from</param>
/// <param name="buffer">The byte buffer</param>
/// <param name="offset">The stream offset</param>
/// <param name="length">The number of bytes to read</param>
/// <param name="timeout">The timeout</param>
/// <returns>The number of read bytes</returns>
private async Task<int> ReadWithTimeout(
NetworkStream stream,
byte[] buffer,
int offset,
int length,
TimeSpan timeout)
{
var tokenSource = new CancellationTokenSource();
var ct = tokenSource.Token;
var task = stream.ReadAsync(buffer, offset, length, ct);
if (await Task.WhenAny(task, Task.Delay(timeout, ct)) == task)
{
tokenSource.Cancel();
return task.Result;
}
tokenSource.Cancel();
throw new ParcelTimeoutException { Notification = this };
}