让Windows Phone更加简单地使用Sockets 已翻译 100%

彭博 投递于 2012/11/27 19:13 (共 5 段, 翻译完成于 11-27)
阅读 221
收藏 0
0
加载中
TcpClient is a class in .NET Framework which “provides simple methods for connecting, sending, and receiving stream data over a network”. TcpClient hides the details of working with sockets and it’s a simple way to open connections and work with TCP. Unfortunately, TcpClient is not available in Windows Phone version of .NET Framework.

已有 1 人翻译此段
我来翻译

SocketEx.TcpClient – Unofficial, only little tested TcpClient for Windows Phone

SocketEx.TcpClient is a MIT-licensed TcpClient for Windows Phone which aims to make working with Windows Phone sockets easy. Compared to the TcpClient in full .NET Framework, SocketEx.TcpClient isn’t 100% compatible and some of the features aren’t implemented at all.

Please note that the library works in a synchronous blocking mode. This means that if you use the TcpClient directly from the UI-thread, you will block the UI from updating.

The library hasn’t gone through an exhaustive testing so there may be issues. The code is based on the “Crystalbyte Networking for Silverlight” project, available from the CodePlex. Almost all of the code is from that neat library, but I adjusted it a little to get it working with Windows Phone and fixed out some threading issues.

已有 1 人翻译此段
我来翻译

The usage

With SocketEx.TcpClient you don’t work with the low-level Socket and SocketAsyncEventArgs-classes. Instead you create a new TcpClient and then operate its stream using either a StreamReader or a StreamWriter. This is easier than it sounds.

I’ve previously written about how to operate with the built-in Socket and SocketAsyncEventArgs classes.

Now, let’s do those same examples with SocketEx.TcpClient.

SocketEx.TcpClient – How To Open a Connection

We can open the connection by passing the server address and server port as parameters to TcpClient.

var serverAddress = "www.google.fi";
var serverPort = 80;
 
var connection = new TcpClient(serverAddress, serverPort);

已有 1 人翻译此段
我来翻译

SocketEx.TcpClient – How To Receive a Message

To read a message we need a StreamReader.

var connection = CreateConnection();
var stream = connection.GetStream();
 
var reader = new StreamReader(stream);
 
string message;
while ((message = reader.ReadLine()) != null)
{
    Debug.WriteLine(message);
}

已有 1 人翻译此段
我来翻译

SocketEx.TcpClient – How To Send a Message

To write a message we need a StreamWriter.

var connection = CreateConnection();
var stream = connection.GetStream();
 
using (var writer = new StreamWriter(stream))
{
    var request = "GET / HTTP/1.1\r\nHost: " + serverAddress + "\r\nConnection: Close\r\n\r\n";
 
    writer.WriteLine(request);
}

已有 1 人翻译此段
我来翻译
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接。
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
加载中

评论(0)

返回顶部
顶部