如何为 Windows Phone 创建和使用 TCP 套接字客户端应用程序【msdn】
2013-02-04 12:06
666 查看
1.连接到 TCP 套接字服务器
使用 System.Net.Sockets API 创建一个套接字并连接到服务器。为了清楚起见,System.Net.Sockets API 的调用被封装在 SocketClient 类中。
定义头(使用 _socket 变量存储 Socket 对象。_clientDone 变量是一个 ManualResetEvent,用于协调通过Sockets API 调用的异步调用):
在 SocketClient.cs 中,添加以下方法,该方法将创建 TCP 套接字,并向服务器发送异步连接请求。此操作的响应将由内联回调进行处理
2.向 TCP 套接字服务器发送数据
3.接收来自 TCP 套接字服务器的数据
使用 System.Net.Sockets API 创建一个套接字并连接到服务器。为了清楚起见,System.Net.Sockets API 的调用被封装在 SocketClient 类中。
定义头(使用 _socket 变量存储 Socket 对象。_clientDone 变量是一个 ManualResetEvent,用于协调通过Sockets API 调用的异步调用):
// Cached Socket object that will be used by each call for the lifetime of this class Socket _socket = null; // Signaling object used to notify when an asynchronous operation is completed static ManualResetEvent _clientDone = new ManualResetEvent(false); // Define a timeout in milliseconds for each asynchronous call. If a response is not received within this // timeout period, the call is aborted. const int TIMEOUT_MILLISECONDS = 5000; // The maximum size of the data buffer to use with the asynchronous socket methods const int MAX_BUFFER_SIZE = 2048;
在 SocketClient.cs 中,添加以下方法,该方法将创建 TCP 套接字,并向服务器发送异步连接请求。此操作的响应将由内联回调进行处理
public string Connect(string hostName, int portNumber) { string result = string.Empty; DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create a SocketAsyncEventArgs object to be used in the connection request SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs(); socketEventArg.RemoteEndPoint = hostEntry; socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) { result = e.SocketError.ToString(); _clientDone.Set(); }); _clientDone.Reset(); _socket.ConnectAsync(socketEventArg); _clientDone.WaitOne(TIMEOUT_MILLISECONDS); return result; }
2.向 TCP 套接字服务器发送数据
public string Send(string data) { string response = "Operation Timeout"; // We are re-using the _socket object that was initialized in the Connect method if (_socket != null) { // Create SocketAsyncEventArgs context object SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs(); // Set properties on context object socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint; socketEventArg.UserToken = null; // Inline event handler for the Completed event. // Note: This event handler was implemented inline in order to make this method self-contained. socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) { response = e.SocketError.ToString(); // Unblock the UI thread _clientDone.Set(); }); // Add the data to be sent into the buffer byte[] payload = Encoding.UTF8.GetBytes(data); socketEventArg.SetBuffer(payload, 0, payload.Length); // Sets the state of the event to nonsignaled, causing threads to block _clientDone.Reset(); // Make an asynchronous Send request over the socket _socket.SendAsync(socketEventArg); // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds. // If no response comes back within this time then proceed _clientDone.WaitOne(TIMEOUT_MILLISECONDS); } else { response = "Socket is not initialized"; } return response; }
3.接收来自 TCP 套接字服务器的数据
public string Receive() { string response = "Operation Timeout"; // We are receiving over an established socket connection if (_socket != null) { // Create SocketAsyncEventArgs context object SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs(); socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint; // Setup the buffer to receive the data socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE); // Inline event handler for the Completed event. // Note: This even handler was implemented inline in order to make this method self-contained. socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { // Retrieve the data from the buffer response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred); response = response.Trim('\0'); } else { response = e.SocketError.ToString(); } _clientDone.Set(); }); // Sets the state of the event to nonsignaled, causing threads to block _clientDone.Reset(); // Make an asynchronous Receive request over the socket _socket.ReceiveAsync(socketEventArg); // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds. // If no response comes back within this time then proceed _clientDone.WaitOne(TIMEOUT_MILLISECONDS); } else { response = "Socket is not initialized"; } return response; } /// <summary> /// Closes the Socket connection and releases all associated resources /// </summary> public void Close() { if (_socket != null) { _socket.Close(); } }
相关文章推荐
- 如何为 Windows Phone 创建和使用 UDP 套接字客户端应用程序
- 如何应用TCP/IP的套接字开发网络通信应用程序
- WebCast《实战ASP.NET AJAX系列课程(2):使用客户端框架创建“纯粹”的Ajax应用程序》相关资源
- 如何使用XCode 4创建ipa文件及提交应用程序
- 如何使用完整客户端创建自己的instant client
- 如何使用 eMbedded Visual C++ 4.0 创建用于 Windows CE 4.1 仿真程序 (Windows CE5.0) 的应用程序
- 如何使用Firebase创建Android聊天应用程序
- 如何使用下面的HTML5功能创建离线的网页和应用程序
- 如何使用XCode 4创建ipa文件及提交应用程序
- MSDN:使用 MFC WinInet 类编写 Internet 客户端应用程序
- [转载MSDN]JavaScript使用面向对象的技术创建高级 Web 应用程序
- 如何应用TCP/IP的套接字开发网络通信应用程序
- Node.js —— 使用net模块创建TCP服务器/客户端
- 如何在 Windows Phone 的代码中创建应用程序栏
- 如何使用C#创建一个三层的数据库应用程序
- 使用 Eclipse 和 Java SE 6 创建独立 Web Services 应用程序,第 2 部分: Web 服务客户端应用程序
- python使用socket创建tcp服务器和客户端
- 一行代码不用敲,15分钟轻松搞定GIS开发,GISer福音,教你如何从下载到使用webappbuilder创建第一个应用程序(不用申请有使用期限的企业账号哦!)
- 使用NetBeans IDE 5.5创建应用程序客户端
- 如何使用XCode 4创建ipa文件及提交应用程序