.Net 的 SocketStream 等效项
Posted
技术标签:
【中文标题】.Net 的 SocketStream 等效项【英文标题】:SocketStream equivalent for .Net 【发布时间】:2013-11-27 21:07:28 【问题描述】:我正在尝试从 Socket 写入和读取 xml,但我不确定如何使用 .Net 执行此操作。 SocketStream 看起来是一种简单的方法,但我没有尝试为 Windows 8 或 Windows phone 构建应用程序。如果有人可以分享一些关于如何使用 .Net 进行等效操作的见解或代码片段,我将不胜感激。
private const string MESSAGE_SERVER_URL = "xmpp.messenger.live.com";
private const string MESSAGE_SERVER_PORT = "5222";
/// <summary>
/// login into live message server
/// </summary>
private async void LoginXMPPServer(string access)
using (StreamSocket client = new StreamSocket())
// connect to server
await client.ConnectAsync(new HostName(MESSAGE_SERVER_URL), MESSAGE_SERVER_PORT);
DataWriter writer = new DataWriter(client.OutputStream);
DataReader reader = new DataReader(client.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
//initialize a stream
string head = "<?xml version='1.0'?>" +
"<stream:stream " +
"to='messenger.live.com' " +
"xmlns='jabber:client' " +
"xmlns:stream='http://etherx.jabber.org/streams' " +
"version='1.0'>";
await SendMessage(head, writer);
string reply = await ReadReplay(reader);
if (reply.Contains("stream:error"))
return;
【问题讨论】:
我已经编辑了您的问题并将[WPF]
标记替换为[.Net ]
标记,因为这与WPF 没有任何关系。
【参考方案1】:
这是一个取自.net SendFile method的例子
// Establish the local endpoint for the socket.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
// Create a TCP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint.
client.Connect(ipEndPoint);
// There is a text file test.txt located in the root directory.
string fileName = "C:\\test.txt";
// Send file fileName to remote device
Console.WriteLine("Sending 0 to the host.", fileName);
client.SendFile(fileName);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
【讨论】:
以上是关于.Net 的 SocketStream 等效项的主要内容,如果未能解决你的问题,请参考以下文章
.NET Framework 3.5 的元组 (.NET 4) 等效项
标准 asp.NET 中的 OnActionExecuting 等效项?