本文整理汇总了C#中System.Net.Sockets.NetworkStream类的典型用法代码示例。如果您正苦于以下问题:C# NetworkStream类的具体用法?C# NetworkStream怎么用?C# NetworkStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
NetworkStream类属于System.Net.Sockets命名空间,在下文中一共展示了NetworkStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Agent
private Thread ziThread; //处理客户端请求的线程
#endregion Fields
#region Constructors
public Agent(TcpClient client, NetworkStream streamToClient, string DataSourceIpOrPortA, string DataSourceIpOrPortB)
{
this.client = client;
this.streamToClient = streamToClient;
this.DataSourceIpOrPortA = DataSourceIpOrPortA;
this.DataSourceIpOrPortB = DataSourceIpOrPortB;
}
示例2: ConnectionContext
public ConnectionContext(NetworkStream clientStream, string connString, TcpTestServer3 server, TaskLoggingHelper log)
{
this.clientStream = clientStream;
this.connString = connString;
this.tcpServer = server;
this.log = log;
}
示例3: ReadVisibleLevelState
/// <summary>
/// Reads a partially observable level state update from the server.
/// </summary>
private async Task ReadVisibleLevelState(NetworkStream stream)
{
Time = await _stream.ReadUInt64();
PlayerPosition = await _stream.ReadPosition();
// removed lock
int roomCount = await _stream.ReadInt32();
for (int i = 0; i < roomCount; ++i)
{
// Each room is identified by its rectangle.
var rect = await _stream.ReadRectangle();
var vis = _visibility.FirstOrDefault(x => x.Rect == rect);
if (vis == null)
{
vis = new RoomVisibility(rect);
_visibility.Add(vis);
}
int tileCount = await _stream.ReadInt32();
for (int j = 0; j < tileCount; ++j)
{
var pos = await _stream.ReadPosition();
vis.Reveal(pos, await TileAppearance.Read(pos, stream), Time);
}
}
LoadedLevel = true;
Program.Draw(this);
Interface.Display.Write(0, 0, Time.ToString());
}
示例4: SendTransportPacket
public static async Task SendTransportPacket(NetworkStream sw, TransportPacketType type, byte[] Data)
{
TransportPacket tp = new TransportPacket(Data, type, Constants.TransportVersion);
byte[] msg = PacketCodec.CreateTransportPacket(tp);
sw.Write(msg, 0, msg.Length);
await sw.FlushAsync();
}
示例5: OutboundPacket
public OutboundPacket(NetworkStream stream, String command)
{
command = "!1" + command;
int dataSize = command.Length + _packetFooter.Length;
int packetSize = _packetHeaderTotalSize + dataSize;
byte[] message = new byte[packetSize];
int pos = 0;
foreach (byte b in _packetHeader)
message[pos++] = b;
foreach (byte b in BitConverter.GetBytes(dataSize).Reverse())
message[pos++] = b;
message[pos++] = _protocolVersion;
pos += 3;
foreach (byte b in System.Text.Encoding.ASCII.GetBytes(command))
message[pos++] = b;
foreach (byte b in _packetFooter)
message[pos++] = b;
stream.Write(message, 0, message.Length);
try { System.Threading.Thread.Sleep(100); } catch (Exception) { }
}
示例6: Response
internal Response(NetworkStream stream)
{
string response;
m_responses = new Queue();
do
{
response = GetLine(stream);
try
{
m_code = InvalidCode;
m_code = int.Parse(response.Substring(0, 3));
}
catch
{
throw new InvalidResponseException("Invalid response", this);
}
m_responses.Enqueue(response);
}
while (response.Length >= 4 && response[3] == '-');
if (m_code == ServiceUnavailable)
throw new ServerDownException(this);
}
示例7: Main
public Main(string userName, string serverSocket, NetworkStream stream)
: this()
{
UserName = userName;
ServerSocket = serverSocket;
Stream = stream;
}
示例8: Build
/// <summary>
/// Build a new SSL steam.
/// </summary>
/// <param name="channel">Channel which will use the stream</param>
/// <param name="socket">Socket to wrap</param>
/// <returns>Stream which is ready to be used (must have been validated)</returns>
public SslStream Build(ITcpChannel channel, Socket socket)
{
var ns = new NetworkStream(socket);
var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);
try
{
X509CertificateCollection certificates = null;
if (Certificate != null)
{
certificates = new X509CertificateCollection(new[] { Certificate });
}
stream.AuthenticateAsClient(CommonName, certificates, Protocols, false);
}
catch (IOException err)
{
throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
}
catch (ObjectDisposedException err)
{
throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
}
catch (AuthenticationException err)
{
throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
}
return stream;
}
示例9: ReadMessage
/// <summary>
/// Blocking call to read a full Message object from a given stream
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static Message ReadMessage(NetworkStream stream)
{
Debug.Assert(stream.CanRead);
byte[] messageBytes = new byte[Message.MaxSize];
byte[] sizeBytes = new byte[4];
int bytesRead = 0;
// Read the initial size from the stream
while (bytesRead < 4)
{
bytesRead += stream.Read(sizeBytes, bytesRead, sizeBytes.Length);
}
int messageSize = BitConverter.ToInt32(sizeBytes, 0);
Debug.Assert(messageSize < Message.MaxSize);
bytesRead = 0;
// Get the message bytes
while (bytesRead < messageSize)
{
bytesRead += stream.Read(messageBytes, bytesRead, messageBytes.Length - bytesRead);
}
// Deserialize the message
return Message.Deserialize(messageBytes);
}
示例10: EstablishConnectionSpecific
/// <inheritdoc />
protected override void EstablishConnectionSpecific()
{
if (btClient == null) ConnectSocket();
//We should now be able to set the connectionInfo localEndPoint
var localEndPoint = btClient.Client.LocalEndPoint as BluetoothEndPoint;
localEndPoint = new BluetoothEndPoint(localEndPoint.Address, ConnectionInfo.RemoteBTEndPoint.Service, localEndPoint.Port);
NetworkComms.UpdateConnectionReferenceByEndPoint(this, ConnectionInfo.RemoteEndPoint, localEndPoint);
ConnectionInfo.UpdateLocalEndPointInfo(localEndPoint);
btClient.Client.ReceiveBufferSize = NetworkComms.MaxReceiveBufferSizeBytes;
btClient.Client.SendBufferSize = NetworkComms.SendBufferSizeBytes;
//We are going to be using the networkStream quite a bit so we pull out a reference once here
btClientNetworkStream = btClient.GetStream();
//Start listening for incoming data
StartIncomingDataListen();
//If the application layer protocol is enabled we handshake the connection
if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled)
ConnectionHandshake();
else
{
//If there is no handshake we can now consider the connection established
TriggerConnectionEstablishDelegates();
//Trigger any connection setup waits
connectionSetupWait.Set();
}
}
示例11: SslStream
public SslStream(
NetworkStream innerStream,
bool leaveInnerStreamOpen,
RemoteCertificateValidationCallback userCertificateValidationCallback
) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback)
{
}
示例12: NetworkClient
public NetworkClient(System.Net.IPAddress serverAddress, int port)
{
TcpClient client = new TcpClient();
client.Connect(serverAddress, port);
_stream = client.GetStream();
_connected = true;
BackgroundWorker streamWorker = new BackgroundWorker();
streamWorker.WorkerSupportsCancellation = true;
streamWorker.DoWork += ReadFromStream;
streamWorker.RunWorkerCompleted += (s, a) =>
{
if (_connected)
{
streamWorker.RunWorkerAsync(_stream);
}
};
streamWorker.RunWorkerAsync(_stream);
StreamError += (ex, stream) =>
{
if (ex is IOException || ex is InvalidOperationException || ex is ObjectDisposedException)
{
_connected = false;
Console.WriteLine("Lost connection: {0}", ex.Message);
Console.Write("> ");
}
else
{
throw ex;
}
};
}
示例13: btnConnect_Click
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
client = new TcpClient("127.0.0.1", 2000);
ns = client.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
String response = sr.ReadLine();
DelegateResponse dr = writeResponse;
dr(response);
randomCoordinates();
string rawData = "Hola mundo";
String data = stringToHexa(rawData);
//Console.WriteLine(data);
sw.WriteLine(data);
sw.Flush();
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
throw;
}
}
示例14: AbsTcpCommunication
public AbsTcpCommunication(TcpClient sock)
{
_sock = sock;
_socketStream = _sock.GetStream ();
_in = new StreamReader (_socketStream);
_out = new StreamWriter (_socketStream);
}
示例15: ChatClient
public ChatClient()
{
this.client = new TcpClient();
this.stream = null;
this.listening = false;
this.listener = new Thread(this.listen);
}