1。 建立Silverlight项目,选择“add a new web to the solution...”,添加Socket Helper Class:
NetWorking.cs:
using System;
using System.Net;
using System.Net.sockets;
using System.Text;
using System.Threading;
namespace SilverlightSocket
{
internal sealed class SocketClIEnt : Idisposable
{
private const int Receive = 1;
private const int Send = 0;
private bool isConnected = false;
private Socket socket;
private DnsEndPoint endPoint;
private IPEndPoint z;
private static autoresetEvent autoEvent = new autoresetEvent(false);
private static autoresetEvent[] autoSendReceiveEvents = new autoresetEvent[]
{
new autoresetEvent(false),
new autoresetEvent(false)
};
internal SocketClIEnt(string host,int port)
{
z = new IPEndPoint(IPAddress.Parse(host),port);
endPoint = new DnsEndPoint(host,port);
socket = new Socket(AddressFamily.InterNetwork
/* hostEndPoint.AddressFamily */,
SocketType.Stream,ProtocolType.Tcp);
}
internal voID Connect()
{
socketasynceventargs args = new socketasynceventargs();
args.UserToken = socket;
args.RemoteEndPoint = z;
args.Completed += new EventHandler<socketasynceventargs>(OnConnect);
socket.ConnectAsync(args);
autoEvent.WaitOne();
if (args.socketError != SocketError.Success)
throw new SocketException((int)args.socketError);
}
internal voID disconnect()
{
socket.Close();
}
#region Events
private voID OnConnect(object sender,socketasynceventargs e)
{
autoEvent.Set();
isConnected = (e.socketError == SocketError.Success);
}
private voID OnReceive(object sender,socketasynceventargs e)
{
autoSendReceiveEvents[Send].Set();
}
private voID OnSend(object sender,socketasynceventargs e)
{
autoSendReceiveEvents[Receive].Set();
if (e.socketError == SocketError.Success)
{
if (e.Lastoperation == SocketAsyncoperation.Send)
{
// Prepare receiving.
Socket s = e.UserToken as Socket;
byte[] response = new byte[255];
e.SetBuffer(response,response.Length);
e.Completed += new EventHandler<socketasynceventargs>(OnReceive);
s.ReceiveAsync(e);
}
}
else
{
ProcessError(e);
}
}
#endregion
private voID ProcessError(socketasynceventargs e)
{
Socket s = e.UserToken as Socket;
if (s.Connected)
{
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
finally
{
if (s.Connected)
s.Close();
}
}
throw new SocketException((int)e.socketError);
}
internal String SendReceive(string message)
{
if (isConnected)
{
Byte[] bytes = EnCoding.UTF8.GetBytes(message);
socketasynceventargs args = new socketasynceventargs();
args.SetBuffer(bytes,bytes.Length);
args.UserToken = socket;
args.RemoteEndPoint = endPoint;
args.Completed += new EventHandler<socketasynceventargs>(OnSend);
socket.SendAsync(args);
autoresetEvent.WaitAll(autoSendReceiveEvents);
return EnCoding.UTF8.GetString(args.Buffer,args.Offset,args.BytesTransferred);
}
else
throw new SocketException((int)SocketError.NotConnected);
}
#region Idisposable Members
public voID dispose()
{
autoEvent.Close();
autoSendReceiveEvents[Send].Close();
autoSendReceiveEvents[Receive].Close();
if (socket.Connected)
socket.Close();
}
#endregion
}
}
在Page.xaml上简单加一个TextBlock用于显示返回字符串,后台文件内容:
...public Page()
{
InitializeComponent();
string host = "127.0.0.1"; //这里本应该是服务器的IP地址,但由于安全原因,目前似乎不可以写成绝对IP地址如:10.235.32.155等。
SocketClIEnt sc = new SocketClIEnt(host,4522);
sc.Connect();
string z = sc.SendReceive("test");
this.ScTxt.Text = z;// System.windows.Application.Current.Host.source.Host;
sc.disconnect(); // 记得不用的时候要断开连接,否则当页面刷新时会产生IOException
}...
2。 服务器端:
建立服务器侦听程序:
using System;
using System.IO;
using System.Net;
using System.Net.sockets;
using System.Text;
class MyTcpListener
{
public static voID Main()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 4522.
Int32 port = 4522;
IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // 同上
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr,port);
// Start Listening for clIEnt requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the Listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You Could also user server.AcceptSocket() here.
TcpClIEnt clIEnt = server.AcceptTcpClIEnt();
Console.Writeline("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = clIEnt.GetStream();
int i;
// Loop to receive all the data sent by the clIEnt.
while ((i = stream.Read(bytes,bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.EnCoding.ASCII.GetString(bytes,i);
Console.Writeline("Received: {0}",data);
// Process the data sent by the clIEnt.
data = data.toupper();
byte[] msg = System.Text.EnCoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg,msg.Length);
Console.Writeline("Sent: {0}",data);
}
Console.Writeline("ClIEnt close.");
// Shutdown and end connection
clIEnt.Close();
}
}
catch (SocketException e)
{
Console.Writeline("SocketException: {0}",e);
}
catch (System.IO.IOException ex)
{
Console.Writeline("IOException: {0}",ex);
}
finally
{
// Stop Listening for new clIEnts.
server.Stop();
}
Console.Writeline("/nHit enter to continue...");
Console.Read();
}
}
3。 运行服务器。
运行第2步中的应用程序。第1次运行时,如果防火墙开启的话,可能会询问是否解除对此进程的阻止,点“解除阻止”。随即打开命令行界面,显示Waiting for a connection...
4。 运行客户端,浏览Silverlight项目中测试页面,显示正确结果TEST。
Socket Helper Class:http://weblogs.asp.net/mschwarz/archive/2008/03/07/silverlight-2-and-sockets.aspx
总结以上是内存溢出为你收集整理的Silverlight2调用Socket完整代码全部内容,希望文章能够帮你解决Silverlight2调用Socket完整代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)