本文整理汇总了C#中NetworkStream类的典型用法代码示例。如果您正苦于以下问题:C# NetworkStream类的具体用法?C# NetworkStream怎么用?C# NetworkStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
NetworkStream类属于命名空间,在下文中一共展示了NetworkStream类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
var m_Config = new ServerConfig
{
Port = 911,
Ip = "Any",
MaxConnectionNumber = 1000,
Mode = SocketMode.Tcp,
Name = "CustomProtocolServer"
};
var m_Server = new CustomProtocolServer();
m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
m_Server.Start();
EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);
using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(serverAddress);
var socketStream = new NetworkStream(socket);
var reader = new StreamReader(socketStream, Encoding.ASCII, false);
string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty);
Random rd = new Random();
var watch = Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
{
int startPos = rd.Next(0, charSource.Length - 2);
int endPos = rd.Next(startPos + 1, charSource.Length - 1);
var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);
byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
socketStream.Write(requestNameData, 0, requestNameData.Length);
var data = Encoding.ASCII.GetBytes(currentMessage);
socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
socketStream.Write(data, 0, data.Length);
socketStream.Flush();
// Console.WriteLine("Sent: " + currentMessage);
var line = reader.ReadLine();
//Console.WriteLine("Received: " + line);
//Assert.AreEqual(currentMessage, line);
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
}
Console.ReadLine();
}
开发者ID:zesus19,项目名称:c5.v1,代码行数:60,代码来源:Program.cs
示例2: NetworkStreamConnection
public void NetworkStreamConnection ()
{
IPEndPoint ipe = new IPEndPoint(Dns.GetHostEntry ("www.google.com").AddressList [0], 80);
Socket s = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
s.Close ();
NetworkStream ns = new NetworkStream (s);
}
开发者ID:Profit0004,项目名称:mono,代码行数:7,代码来源:NetworkStreamTest.cs
示例3: PostStream
static string PostStream (Mono.Security.Protocol.Tls.SecurityProtocolType protocol, string url, byte[] buffer)
{
Uri uri = new Uri (url);
string post = "POST " + uri.AbsolutePath + " HTTP/1.0\r\n";
post += "Content-Type: application/x-www-form-urlencoded\r\n";
post += "Content-Length: " + (buffer.Length + 5).ToString () + "\r\n";
post += "Host: " + uri.Host + "\r\n\r\n";
post += "TEST=";
byte[] bytes = Encoding.Default.GetBytes (post);
IPHostEntry host = Dns.Resolve (uri.Host);
IPAddress ip = host.AddressList [0];
Socket socket = new Socket (ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect (new IPEndPoint (ip, uri.Port));
NetworkStream ns = new NetworkStream (socket, false);
SslClientStream ssl = new SslClientStream (ns, uri.Host, false, protocol);
ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);
ssl.Write (bytes, 0, bytes.Length);
ssl.Write (buffer, 0, buffer.Length);
ssl.Flush ();
StreamReader reader = new StreamReader (ssl, Encoding.UTF8);
string result = reader.ReadToEnd ();
int start = result.IndexOf ("\r\n\r\n") + 4;
start = result.IndexOf ("\r\n\r\n") + 4;
return result.Substring (start);
}
开发者ID:Jakosa,项目名称:MonoLibraries,代码行数:28,代码来源:postecho.cs
示例4: SendCommand
void SendCommand(NetworkStream stream, byte command, byte[] host, int port)
{
byte[] request = new byte[9];
request[0] = Version;
request[1] = command;
request[2] = (byte)(port / 256);
request[3] = (byte)(port % 256);
host.CopyTo(request, 4);
request[8] = 0;
stream.Write(request, 0, request.Length);
byte[] response = new byte[8];
stream.Read(response, 0, response.Length);
// check null byte
if (response[0] != 0)
throw new Socks4Exception("Server response: invalid null byte");
switch (response[1])
{
case Reply.RequestGranted:
return;
case Reply.RequestRejectedOrFailed:
throw new Socks4Exception("Server response: request rejected or failed");
case Reply.ClientNotIdent:
throw new Socks4Exception("Server response: request failed because client is not running identd (or not reachable from the server)");
case Reply.ClientIdentUserIDFailed:
throw new Socks4Exception("request failed because client's identd could not confirm the user ID string in the request");
default:
throw new Socks4Exception("Server response: unknown reply");
}
}
开发者ID:Zergatul,项目名称:ZergatulLib,代码行数:30,代码来源:Socks4.cs
示例5: certConnectReply
public void certConnectReply(byte[] packet, NetworkStream client)
{
// Just send the viewData
byte[] response = { 0x04, 0x00, 0x00, 0x00, 0x00 };
byte[] encryptedResponse = marginEncr.encrypt(response);
sendTCPVariableLenPacket(encryptedResponse, client);
}
开发者ID:hdneo,项目名称:mxo-hd,代码行数:7,代码来源:MarginClient.cs
示例6: Main
public static void Main()
{
TcpListener tcpListener = new TcpListener(10);
tcpListener.Start();
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
Console.WriteLine("Client connected");
NetworkStream networkStream = new NetworkStream(socketForClient);
System.IO.StreamWriter streamWriter =
new System.IO.StreamWriter(networkStream);
System.IO.StreamReader streamReader =
new System.IO.StreamReader(networkStream);
string theString = "Sending";
streamWriter.WriteLine(theString);
Console.WriteLine(theString);
streamWriter.Flush();
theString = streamReader.ReadLine();
Console.WriteLine(theString);
streamReader.Close();
networkStream.Close();
streamWriter.Close();
}
socketForClient.Close();
Console.WriteLine("Exiting...");
}
开发者ID:dbremner,项目名称:hycs,代码行数:26,代码来源:AsyIOServer.cs
示例7: TestCustomProtocol
public void TestCustomProtocol()
{
EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);
using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(serverAddress);
var socketStream = new NetworkStream(socket);
var reader = new StreamReader(socketStream, Encoding.ASCII, false);
var writer = new StreamWriter(socketStream, Encoding.ASCII, 1024);
string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty);
Random rd = new Random();
for (int i = 0; i < 10; i++)
{
int startPos = rd.Next(0, charSource.Length - 2);
int endPos = rd.Next(startPos + 1, charSource.Length - 1);
var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);
writer.Write("ECHO {0} {1}", currentMessage.Length.ToString().PadLeft(4, '0'), currentMessage);
writer.Flush();
var line = reader.ReadLine();
Console.WriteLine("Received: " + line);
Assert.AreEqual(currentMessage, line);
}
}
}
开发者ID:xxjeng,项目名称:nuxleus,代码行数:34,代码来源:CustomProtocolServerTest.cs
示例8: TestBatchRequest
public void TestBatchRequest()
{
using (var socket = CreateClient())
{
var socketStream = new NetworkStream(socket);
using (var reader = new StreamReader(socketStream, Encoding.ASCII, true))
using (var writer = new ConsoleWriter(socketStream, Encoding.ASCII, 1024 * 8))
{
reader.ReadLine();
int size = 100;
var lines = new string[size];
for (var i = 0; i < size; i++)
{
var line = Guid.NewGuid().ToString();
lines[i] = line;
var request = CreateRequest(line);
writer.Write(request);
}
writer.Flush();
for (var i = 0; i < size; i++)
{
var receivedLine = reader.ReadLine();
Assert.AreEqual(lines[i], receivedLine);
}
}
}
}
开发者ID:huamanhtuyen,项目名称:TagLo2,代码行数:32,代码来源:ProtocolTestBase.cs
示例9: BackupProcess
static void BackupProcess()
{
Console.WriteLine("I am backup!");
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener listener = new TcpListener(ipAddress, port);
listener.Start();
Socket sock = listener.AcceptSocket();
Stream str = new NetworkStream(sock);
StreamReader sr = new StreamReader(str);
string line = "-1";
try
{
while (true)
line = sr.ReadLine();
}
catch(IOException)
{
sr.Close();
listener.Stop();
PrimaryProcess(Convert.ToInt32(line) + 1);
}
}
开发者ID:DanglingPointer,项目名称:TTK4145,代码行数:26,代码来源:Program.cs
示例10: HandleRequest
public void HandleRequest(Url url, NetworkStream stream)
{
foreach (IPlugin p in plugins)
{
p.handleRequest(url, stream);
}
}
开发者ID:karinmae,项目名称:SWE1,代码行数:7,代码来源:PluginManager.cs
示例11: Game
public Game(NetworkStream ns, string op_name)
{
InitializeComponent();
GridX = new int[15];
GridY = new int[10];
Network_Stream = ns;
arr = new char[19, 29];
lines = new int[29];
player1 = new Player();
client = new Client();
player1.OpponentName = op_name;
if (Player.IsServer)
{
turn = Player.Name;
waiting = player1.OpponentName;
}
else
{
turn = player1.OpponentName;
waiting = Player.Name;
}
Thread read = new Thread(() => Read_Stream());
read.IsBackground = true;
read.Start();
}
开发者ID:umar-qureshi2,项目名称:UG-Courses,代码行数:27,代码来源:Game.cs
示例12: TestWorkerIncompleteData
public void TestWorkerIncompleteData()
{
StringBuilder output = new StringBuilder();
Process worker;
TcpListener CSharpRDD_SocketServer = CreateServer(output, out worker);
using (var serverSocket = CSharpRDD_SocketServer.AcceptSocket())
using (var s = new NetworkStream(serverSocket))
{
WriteWorker(s);
SerDe.Write(s, command.Length);
s.Write(command, 0, command.Length);
for (int i = 0; i < 100; i++)
SerDe.Write(s, i.ToString());
int count = 0;
foreach (var bytes in ReadWorker(s, 100))
{
Assert.AreEqual(count++.ToString(), Encoding.UTF8.GetString(bytes));
}
Assert.AreEqual(100, count);
}
AssertWorker(worker, output, -1, "System.NullReferenceException: Object reference not set to an instance of an object.");
CSharpRDD_SocketServer.Stop();
}
开发者ID:zhangf911,项目名称:SparkCLR,代码行数:30,代码来源:WorkerTest.cs
示例13: ConnectCompleted
void ConnectCompleted( Socket sock )
{
if ( sock == null )
{
OnDisconnected( EventArgs.Empty );
return;
}
if ( !sock.Connected )
{
DebugLog.WriteLine( "TcpConnection", "Unable to connect" );
OnDisconnected( EventArgs.Empty );
return;
}
DebugLog.WriteLine( "TcpConnection", "Connected!" );
isConnected = true;
netStream = new NetworkStream( sock, false );
netReader = new BinaryReader( netStream );
netWriter = new BinaryWriter( netStream );
// initialize our network thread
netThread = new Thread( NetLoop );
netThread.Name = "TcpConnection Thread";
netThread.Start();
OnConnected( EventArgs.Empty );
}
开发者ID:Redflameman0,项目名称:SteamKit2,代码行数:31,代码来源:TcpConnection.cs
示例14: SendXContent
public static void SendXContent(NetworkStream nstm, byte[] content, int offset, int length)
{
byte[] balen = IntHexBytes(length); // Don't use LongLength here because nstm.Write only uses int anyway.
nstm.Write(balen, 0, balen.Length);
nstm.Write(content, offset, length);
}
开发者ID:erisonliang,项目名称:qizmt,代码行数:7,代码来源:XContent.cs
示例15: GetConnectionDetails
private static ConnectionDetails GetConnectionDetails(NetworkStream networkStream, TcpClient tcpClient)
{
// read the header and check that it is a GET request
string header = HttpHelper.ReadHttpHeader(networkStream);
Regex getRegex = new Regex(@"^GET(.*)HTTP\/1\.1");
Match getRegexMatch = getRegex.Match(header);
if (getRegexMatch.Success)
{
// extract the path attribute from the first line of the header
string path = getRegexMatch.Groups[1].Value.Trim();
// check if this is a web socket upgrade request
Regex webSocketUpgradeRegex = new Regex("Upgrade: websocket");
Match webSocketUpgradeRegexMatch = webSocketUpgradeRegex.Match(header);
if (webSocketUpgradeRegexMatch.Success)
{
return new ConnectionDetails(networkStream, tcpClient, path, ConnectionType.WebSocket, header);
}
else
{
return new ConnectionDetails(networkStream, tcpClient, path, ConnectionType.Http, header);
}
}
else
{
return new ConnectionDetails(networkStream, tcpClient, string.Empty, ConnectionType.Unknown, header);
}
}
开发者ID:modulexcite,项目名称:websocket-server,代码行数:30,代码来源:WebServer.cs
示例16: HttpClient
internal HttpClient(Socket socket, HttpServer server)
{
this.server = server;
this.socket = socket;
IPEndPoint remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
isConnected = true;
this.remoteAddress = remoteEndPoint.Address.ToString();
this.remotePort = remoteEndPoint.Port;
server.Stopping += new EventHandler(server_Stopping);
stream = new NetworkStream(socket, true);
try
{
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReceiveData), this);
}
catch(IOException)
{
Disconnect();
throw;
}
server.OneHertzTick += new EventHandler(server_OneHertzTick);
}
开发者ID:xuchuansheng,项目名称:GenXSource,代码行数:25,代码来源:HttpClient.cs
示例17: ConnectCompleted
void ConnectCompleted( object sender, SocketAsyncEventArgs e )
{
sock = sender as Socket;
if ( sock == null )
{
OnDisconnected( EventArgs.Empty );
return;
}
if ( e.SocketError != SocketError.Success )
{
DebugLog.WriteLine( "TcpConnection", "Unable to connect: {0}", e.SocketError );
OnDisconnected( EventArgs.Empty );
return;
}
DebugLog.WriteLine( "TcpConnection", "Connected!" );
isConnected = true;
netStream = new NetworkStream( sock, false );
netReader = new BinaryReader( netStream );
netWriter = new BinaryWriter( netStream );
// initialize our network thread
netThread = new Thread( NetLoop );
netThread.Name = "TcpConnection Thread";
netThread.Start();
OnConnected( EventArgs.Empty );
}
开发者ID:KimimaroTsukimiya,项目名称:SteamBot-1,代码行数:33,代码来源:TcpConnection.cs
示例18: Client
public Client(String host, Int32 port)
{
try
{
clientName = Dns.GetHostName();
}
catch (SocketException se)
{
MessageBox.Show("ERROR: Could not retrieve client's DNS hostname. Please try again." + se.Message + ".", "Client Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
serverName = host;
gamePort = port;
client = new TcpClient(host, port);
netStream = client.GetStream();
reader = new StreamReader(netStream);
writer = new StreamWriter(netStream);
ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
cert = new X509Certificate2("server.crt");
ssl.AuthenticateAsClient(serverName);
writer.AutoFlush = true;
}
开发者ID:Team7-SoftEng,项目名称:GateofGabethulu-launcher,代码行数:27,代码来源:Client.cs
示例19: checkConflict
public void checkConflict()
{
Server_Client.Client client= new Server_Client.Client();
this.tcpClient = client.Connect(Luu.IP, Luu.Ports);
Entities.KhoHang kh = new Entities.KhoHang("Select");
Entities.KhoHang[] kh1 = new Entities.KhoHang[1];
networkStream = client.SerializeObj(this.tcpClient, "KhoHang", kh);
kh1 = (Entities.KhoHang[])client.DeserializeHepper1(networkStream, kh1);
if (kh1 != null)
{
for (int j = 0; j < kh1.Length; j++)
{
if (kh1[j].MaKho == txtMaKho.Text)
{
MessageBox.Show("Thất bại");
chck = "No";
txtMaKho.Text = new Common.Utilities().ProcessID(txtMaKho.Text);
break;
}
else
chck = "Yes";
}
}
}
开发者ID:mrk29vn,项目名称:vna-accounting,代码行数:26,代码来源:frmSuaKhoHang.cs
示例20: Main
static void Main (string [] args)
{
int i = 0;
while (args [i].StartsWith ("-")){
if (args [i] == "-debug")
debug = true;
if (args [i] == "-headers")
headers = true;
if (args [i] == "-header")
header = args [++i];
i++;
}
c = new TcpClient (args [i], Int32.Parse (args [i+1]));
c.ReceiveTimeout = 1000;
ns = c.GetStream ();
sw = new StreamWriter (ns);
sr = new StreamReader (ns);
string host = args [i];
if (args [i+1] != "80")
host += ":" + args [i+1];
send (String.Format ("GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n", args [i+2], host));
MemoryStream ms = new MemoryStream ();
try {
byte [] buf = new byte [1024];
int n;
while ((n = ns.Read (buf, 0, 1024)) != 0){
ms.Write (buf, 0, n);
}
} catch {}
ms.Position = 0;
sr = new StreamReader (ms);
string s;
while ((s = sr.ReadLine ()) != null){
if (s == ""){
if (headers)
return;
string x = sr.ReadToEnd ();
Console.Write (x);
break;
} else {
if (debug || headers)
Console.WriteLine (s);
if (header != null && s.StartsWith (header)){
Console.WriteLine (s);
return;
}
}
}
}
开发者ID:nobled,项目名称:mono,代码行数:60,代码来源:rtest.cs
注:本文中的NetworkStream类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论