本文整理汇总了C#中NetworkStream.ReadByte方法的典型用法代码示例。如果您正苦于以下问题:C# NetworkStream.ReadByte方法的具体用法?C# NetworkStream.ReadByte怎么用?C# NetworkStream.ReadByte使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类NetworkStream
的用法示例。
在下文中一共展示了NetworkStream.ReadByte方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReadInt32
static public int ReadInt32(NetworkStream ns)
{
return (ns.ReadByte() << 24)
| (ns.ReadByte() << 16)
| (ns.ReadByte() << 8)
| (ns.ReadByte());
}
示例2: ReadString
private static string ReadString(NetworkStream stream)
{
StringBuilder text = new StringBuilder();
var aa = (char)stream.ReadByte();
while (aa != 0)
{
text.Append(aa);
aa = (char)stream.ReadByte();
}
return text.ToString();
}
示例3: InMemory
public InMemory(ulong contentLength, NetworkStream networkStream, Socket socket)
{
Content = new byte[contentLength];
int sleepTime = 10;
for (uint ctr = 0; ctr < contentLength; )
{
if (!socket.Connected)
throw new SocketDisconnected();
int notByte = networkStream.ReadByte();
if (notByte >= byte.MinValue || notByte <= byte.MaxValue)
{
Content[ctr] = Convert.ToByte(notByte);
ctr++;
sleepTime = 10;
}
else
{
Thread.Sleep(sleepTime);
sleepTime = sleepTime * 2;
if (sleepTime >= 200)
sleepTime = 200;
}
}
}
示例4: ReadString
public static string ReadString(NetworkStream _NetworkStream)
{
using (MemoryStream _MemoryStream = new MemoryStream())
{
try
{
while (true)
{
int _byte = _NetworkStream.ReadByte();
if (_byte == -1) break;
_MemoryStream.WriteByte((byte)_byte);
if (_byte == 10)
{
string s = ASCIIEncoding.ASCII.GetString(_MemoryStream.ToArray());
//Trace.WriteLine("<<<<<<<<string received>>>>>>>" + s.Length);
return s;
}
Thread.Sleep(10);
}
}
catch (IOException)
{
//Trace.WriteLine(e.Message);
}
}
return null;
}
示例5: Connect
// методы работы с исходящим подключением
/// <summary>
/// Запускает процесс поиска маршрута
/// </summary>
/// <param name="target">Целевой компьютер</param>
/// <param name="mat">Ид раздачи</param>
/// <returns>Сокет, подключенный к следующему компьютеру в цепочке, либо null, если маршрут не удалось установить</returns>
public Socket Connect(Client target, int mat)
{
foreach (Material m in ProgramMaterials.MaterialsArray)
{
foreach (Connection c in m.Connections)
{
try
{
IPAddress ip = ((IPEndPoint)c.Socket.RemoteEndPoint).Address;
short port = 30095;
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
try { sock.Connect(ip, port); }
catch (Exception) { continue; }
NetworkStream comStr = new NetworkStream(sock);
comStr.WriteByte((byte)IDT_Protocol.Connect);
int resp = comStr.ReadByte();
if(resp != (int)IDT_Protocol.Connected)
{ TerminateConnection(comStr); continue; }
byte[] temp = target.Serialize();
comStr.WriteByte((byte)IDT_Protocol.IsLink);
comStr.Write(temp, 0, 6);
resp = comStr.ReadByte();
if(resp != (int)IDT_Protocol.LinkAccesible)
{ TerminateConnection(comStr); continue; }
comStr.WriteByte((byte)IDT_Protocol.IsMaterial);
comStr.Write(bc.GetBytes(mat), 0, 4);
IDT_Protocol res = (IDT_Protocol)comStr.ReadByte();
if(res == IDT_Protocol.MaterialNotFound)
comStr.WriteByte((byte)IDT_Protocol.TerminateTransaction);
return sock;
}
catch (Exception)
{
continue;
}
}
}
return null;
}
示例6: receiveData
public static void receiveData()
{
try
{
//Creating listening Socket
listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 7000);
Console.WriteLine("Waiting for server response");
//Starts listening
listener.Start();
//Establish connection upon server request
while (true)
{
socket = listener.AcceptSocket();
Console.WriteLine("Connetion is established");
//Fetch the messages from the server
int asw = 0;
int count = 2;
//create a network stream using connecion
NetworkStream serverStream = new NetworkStream(socket);
List<Byte> inputStr = new List<byte>();
//fetch messages from server
while (asw != -1)
{
count++;
asw = serverStream.ReadByte();
inputStr.Add((Byte)asw);
}
String messageFromServer = Encoding.UTF8.GetString(inputStr.ToArray());
Console.WriteLine("Response from server to join ");
torkenizer.tokenizeMessage(messageFromServer);
Console.WriteLine(messageFromServer);
serverStream.Close(); //close the netork stream
}
}
catch (Exception e)
{
Console.WriteLine("Communication (RECEIVING) Failed! \n " + e.StackTrace);
error= true;
}
finally
{
if (socket != null)
if (socket.Connected)
socket.Close();
if (error)
receiveData();
}
}
示例7: readTextTCP
/// <summary>
/// Reads the text from the server/client
/// </summary>
/// <returns>
/// The text.
/// </returns>
/// <param name='io'>
/// Network stream for reading from the server/client.
/// </param>
public static String readTextTCP(NetworkStream io)
{
String line = "";
char ch;
while((ch = (char)io.ReadByte()) != 0)
line += ch;
return line;
}
示例8: ReadLine
/// <summary>
/// Reads a line from the stream in a way such that it does not create a
/// <see cref="StreamReader"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="NetworkStream"/> to read from.
/// </param>
/// <returns>
/// The line read from the stream.
/// </returns>
public static string ReadLine(NetworkStream stream)
{
System.Text.StringBuilder line = new System.Text.StringBuilder();
int ich;
while( (ich = stream.ReadByte()) > -1 )
{
char ch = (char) ich;
if( ch == '\n' ) break;
if( ch != '\r' )
line.Append(ch);
}
return line.ToString();
}
示例9: receiveData
public void receiveData()
{
try
{
Console.WriteLine("Recieve Data Running");
TcpListener listner = new TcpListener(IPAddress.Parse("127.0.0.1"), 7000);
string msg = null;
listner.Start();
parser p2 = new parser();
while (true)
{
try
{
Socket s = listner.AcceptSocket();
if (s.Connected)
{
NetworkStream stream = new NetworkStream(s);
List<Byte> inputStr = new List<byte>();
int asw = 0;
while (asw != -1)
{
asw = stream.ReadByte();
inputStr.Add((Byte)asw);
}
msg = Encoding.UTF8.GetString(inputStr.ToArray());
//Console.WriteLine(reply);
//stream.Close();
//listner .Stop();
//gameViwe.drow(msg);
p2.evaluate(msg);
}
//Console.WriteLine(msg);
gameView.ShowDialog();
}
catch
{
//Console.WriteLine("Error");
}
}
}
catch
{
Console.WriteLine("Error- Finished");
return ;
}
//listner.Stop();
}
示例10: HandleSocks4
private void HandleSocks4(Socket socket, ChannelDirectTcpip channel)
{
using (var stream = new NetworkStream(socket))
{
var commandCode = stream.ReadByte();
// TODO: See what need to be done depends on the code
var portBuffer = new byte[2];
stream.Read(portBuffer, 0, portBuffer.Length);
var port = (uint)(portBuffer[0] * 256 + portBuffer[1]);
var ipBuffer = new byte[4];
stream.Read(ipBuffer, 0, ipBuffer.Length);
var ipAddress = new IPAddress(ipBuffer);
var username = ReadString(stream);
var host = ipAddress.ToString();
this.RaiseRequestReceived(host, port);
channel.Open(host, port, socket);
stream.WriteByte(0x00);
if (channel.IsOpen)
{
stream.WriteByte(0x5a);
}
else
{
stream.WriteByte(0x5b);
}
stream.Write(portBuffer, 0, portBuffer.Length);
stream.Write(ipBuffer, 0, ipBuffer.Length);
}
}
示例11: RequestPart
/// <summary>
/// Метод запрашивает часть данных у подключенного IDT сервиса, либо конечного компьютера и отправляет ее инициатору подключения -
/// другому IDT сервису, либо первому компьютеру в цепочке
/// </summary>
/// <param name="c">Объект подключения с инициатором</param>
/// <param name="sock">Сокет, подключенный к следующему компьютеру в цепочке</param>
/// <param name="material">Идентификатор раздачи</param>
/// <param name="targetHost">Целевой компьютер, для достижения которого строилась цепочка</param>
private void RequestPart(Connection c, Socket sock, int material, Client targetHost)
{
NetworkStream nStream = new NetworkStream(sock);
NetworkStream ansStream = new NetworkStream(c.Socket);
byte[] bcom = new byte[] { (byte)C_C_Protocol.GetPart };
byte[] bmat = bc.GetBytes(material);
byte[] bfile = new byte[4];
byte[] bpart = new byte[4];
byte[] bsize = new byte[4];
ansStream.Read(bfile, 0, 4);
ansStream.Read(bpart, 0, 4);
ansStream.Read(bsize, 0, 4);
int size = bc.ToInt32(bsize, 0);
// Работа в режиме целевого компьютера
if (IsTarget(sock, targetHost))
{
nStream.Write(bcom, 0, 1);
nStream.Write(bmat, 0, 1);
nStream.Write(bfile, 0, 4);
nStream.Write(bpart, 0, 4);
C_C_Protocol resp = (C_C_Protocol)nStream.ReadByte();
int ispart = nStream.ReadByte();
if (resp != C_C_Protocol.SendPart || ispart == 0)
{
ansStream.WriteByte((byte)IDT_Protocol.SendPart);
ansStream.WriteByte(0);
return;
}
nStream.Read(new byte[12], 0, 12);
byte[] buffer = new byte[size];
for (int i = 0; i != size; )
{
i += nStream.Read(buffer, i, size - i);
}
ansStream.WriteByte((byte)IDT_Protocol.SendPart);
ansStream.WriteByte(0);
ansStream.Write(buffer, 0, size);
}
else//работа в режиме промежуточной ячейки сети
{
IDT_Protocol resp = (IDT_Protocol) nStream.ReadByte();
int status = nStream.ReadByte();
if (resp != IDT_Protocol.SendPart) return;
if (status == 0)
{
ansStream.WriteByte((byte)IDT_Protocol.SendPart);
ansStream.WriteByte((byte)status);
return;
}
byte[] buffer = new byte[size];
for (int i = 0; i != size; )
{
i += nStream.Read(buffer, i, size - i);
}
ansStream.WriteByte((byte)IDT_Protocol.SendPart);
ansStream.WriteByte((byte)status);
ansStream.Write(buffer, 0, size);
}
}
示例12: CheckMaterial
/// <summary>
/// Проверяет наличие раздачи на конечном компютере, команда передается по цепочке
/// </summary>
/// <param name="c">Объект подключения с инициатором</param>
/// <param name="sock">Сокет, подключенный к следующему компьютеру в цепочке</param>
/// <param name="targetHost">Целевой компьютер, для достижения которого строилась цепочка</param>
/// <returns>Возвращает номер раздачи, полученный от предыдущего компьютера в цепи</returns>
private int CheckMaterial(Connection con, Socket sock, Client targetHost)
{
NetworkStream nStream = new NetworkStream(sock);
NetworkStream ansStream = new NetworkStream(con.Socket);
byte[] temp = new byte[4];
ansStream.Read(temp, 0, 4);
int material = bc.ToInt32(temp,0);
if (IsTarget(sock, targetHost)) // работа в режиме целевого хоста
{
nStream.Write(new byte[] {(byte)C_C_Protocol.IsMaterial},0,1);
nStream.Write(temp, 0, 4);
byte[] resp = new byte[6];
nStream.Read(resp,0,6);
if (resp[5] == 1)
{
ansStream.Write(new byte[] { (byte)IDT_Protocol.MaterialConfirmed }, 0, 1);
return material;
}
else
{
ansStream.Write(new byte[] { (byte)IDT_Protocol.MaterialNotFound }, 0, 1);
return 0;
}
}
else // работа в режиме ячейки
{
nStream.Write(new byte[] { (byte)C_C_Protocol.IsMaterial }, 0, 1);
IDT_Protocol resp = (IDT_Protocol)nStream.ReadByte();
if (resp == IDT_Protocol.MaterialNotFound)
return 0;
else return material;
}
}
示例13: IDTSession
/// <summary>
/// Процедура, содержащая цикл обработки команд протокола IDT
/// </summary>
/// <param name="con">Объект подключения с инициатором сеанса</param>
private void IDTSession(object con)
{
Connection c = (Connection)con;
NetworkStream nStream = new NetworkStream(c.Socket);
/*общие данные*/
Socket sock = null;
int material = 0;
Client targetHost = new Client() ;
IDT_Protocol com = (IDT_Protocol)nStream.ReadByte();
nStream.Close();
switch (com)
{
case IDT_Protocol.IsLink:
targets.Add(targetHost);
sock = TryConnect(c, out targetHost, material);
break;
case IDT_Protocol.IsMaterial:
material = CheckMaterial(c,sock, targetHost);
break;
case IDT_Protocol.GetPart:
RequestPart(c, sock, material, targetHost);
break;
case IDT_Protocol.TerminateTransaction:
targets.Remove(targetHost);
break;
}
}
示例14: ListenQuery
static void ListenQuery(object Handle)
{
int CH = (int)Handle;
Socket ConSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
ConSock.Connect(RemoteServer, RemotePort);
List<byte> ConBuffer = new List<byte>();
NetworkStream NS = new NetworkStream(ClientSocket[CH]);
while (true)
{
int b = NS.ReadByte();
if (b == -1) break;
ConBuffer.Add((byte)b);
}
NS.Flush();
}
catch (Exception ex)
{
Console.WriteLine("CON " + CH + " > " + ex.Message);
goto the_end;
}
int IndexOfSent = 0;
int IndexOfRecv = 0;
while (ClientSocket[CH].Connected)
{
try
{
List<byte> XBuffer = new List<byte>();
Connection Formx = new Connection(); // DI
Formx.Text = $"CONNECTION #{CH} STATUS"; // DI
// MegaForm.Invoke((MethodInvoker)delegate () { Formx.Show(); }); // DI
while (ClientSocket[CH].Available == 0) Thread.Sleep(1);
MegaForm.Invoke((MethodInvoker)delegate () { IndexOfSent = MegaForm.LB.Items.Add($"C{CH}: Data Available: {ClientSocket[CH].Available}"); }); // DI
while (true)
{
NetworkStream NS = new NetworkStream(ClientSocket[CH]);
int b = NS.ReadByte();
if (b == -1) break;
XBuffer.Add((byte)b);
}
Console.WriteLine("CON " + CH + " > " + "DATA UPSTREAM GATHERED");
// MegaForm.Invoke((MethodInvoker)delegate () { IndexOfSent = MegaForm.LB.Items.Add($"C{CH}: Data Sent: {XBuffer.Count}"); }); // DI
ConSock.Send(XBuffer.ToArray());
if (ConSock.Connected)
{
Console.WriteLine("CON " + CH + " > " + "STATUS 2 STARTED");
List<byte> RBuffer = new List<byte>();
NetworkStream OutStream = new NetworkStream(ConSock);
NetworkStream InStream = new NetworkStream(ClientSocket[CH]);
Console.WriteLine("CON " + CH + " > " + "NETSTREAM THREADED");
while (true)
{
int b = OutStream.ReadByte();
if (b == -1) break;
RBuffer.Add((byte)b);
InStream.WriteByte((byte)b);
}
InStream.Flush();
Console.WriteLine("CON " + CH + " > " + "BUFFER WRITTEN!");
MegaForm.Invoke((MethodInvoker)delegate () { IndexOfRecv = MegaForm.LR.Items.Add($"C{CH}: Data Recv: {RBuffer.Count}"); }); // DI
}
else break;
// NS.Flush();
}
catch (Exception ex)
{
string rq = "HTTP/1.0 464 Median Error\r\nContent-Length: " + ex.Message.Length + "\r\n\r\n" + ex.Message;
Console.WriteLine("CON " + CH + " > " + ex.Message);
ClientSocket[CH].Send(Encoding.ASCII.GetBytes(rq));
break;
}
Thread.Sleep(10);
}
the_end:
ConSock.Close();
ClientSocket[CH].Close();
ClientSocket[CH] = null;
ClientThread[CH].Abort();
ClientThread[CH] = null;
Console.WriteLine("CON " + CH + " > " + "TRANSMISSION TERMINATED");
}
示例15: GetPart
/// <summary>
/// Запрашивает файл по цепочке компьютеров
/// </summary>
/// <param name="sock">Адрес следующей ячеки сети</param>
/// <param name="file">Номер файла в раздаче</param>
/// <param name="part">Номер части файла</param>
/// <param name="size">Размер части</param>
/// <returns>Скачанную часть</returns>
public byte[] GetPart(Socket sock, int file,int part,int size)
{
try
{
NetworkStream nStream = new NetworkStream(sock);
nStream.WriteByte((byte)IDT_Protocol.GetPart);
byte[] bFile = bc.GetBytes(file);
byte[] bPart = bc.GetBytes(part);
byte[] bSize = bc.GetBytes(size);
nStream.Write(bFile, 0, 4);
nStream.Write(bPart, 0, 4);
nStream.Write(bSize, 0, 4);
IDT_Protocol resp = (IDT_Protocol) nStream.ReadByte();
int stat = nStream.ReadByte();
if (resp != IDT_Protocol.SendPart || stat == 0)
return new byte[0];
byte[] buffer = new byte[size];
for (int i = 0; i != size; )
{
i += nStream.Read(buffer, i, size - i);
}
return buffer;
}
catch (SocketException)
{
return new byte[0];
}
}