在.net中定义以下
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ClientSocket
{
public class AsynchronousSocketListener
{
//异步socket诊听
// Incoming data from client.从客户端传来的数据
public static string data = null;
// Thread signal.线程 用一个指示是否将初始状态设置为终止的布尔值初始化 ManualResetEvent 类的新实例。
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Data buffer for incoming data. 传入数据缓冲
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket. 建立本地端口
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11001);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and listen for incoming connections.绑定端口和数据
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.设置无信号状态的事件
allDone.Reset();
// Start an asynchronous socket to listen for connections.重新 启动异步连接
Console.WriteLine("Waiting for a connection..."+localEndPoint.Address+" : "+localEndPoint.Port);
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener );
// Wait until a connection is made before continuing.等待连接创建后继续
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.接受回调方法 该方法的此节向主应用程序线程发出信号,让它继续处理并建立与客户端的连接
allDone.Set();
// Get the socket that handles the client request.获取客户端请求句柄
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
/// <summary>
/// 与接受回调方法一样,读取回调方法也是一个 AsyncCallback 委托。该方法将来自客户端套接字的一个或多个字节读入数据缓冲区,然后再次调用 BeginReceive 方法,直到客户端发送的数据完成为止。从客户端读取整个消息后,在控制台上显示字符串,并关闭处理与客户端的连接的服务器套接字。
/// </summary>
/// <param name="ar">IAsyncResult 委托</param>
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
Console.WriteLine("收到连接信号");
// Retrieve the state object and the handler socket创建自定义的状态对象
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;//处理的句柄
// Read data from the client socket. 读出
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
Console.WriteLine("数据量 = "+bytesRead);
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.UTF8.GetString(
state.buffer,0,bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<") > -1)
{
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content );
// Echo the data back to the client.
Send(handler, "回执:"+content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using UTF8 encoding.
byte[] byteData = Encoding.UTF8.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
/// <summary>
/// 发送
/// </summary>
/// <param name="ar"></param>
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket) ar.AsyncState;
// Complete sending the data to the remote device.向远端发送数据
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
}
Flash端
var socket:XMLSocket = new XMLSocket();
socket.onConnect = function(success:Boolean) {
if (success) {
trace("Connection succeeded!");
} else {
trace("Connection failed!");
}
};
if (!socket.connect("127.0.0.1", 11001)) {
trace("Connection failed!");
}
socket.onXML = function(doc) {
/*var e = doc.firstChild;
if (e != null && e.nodeName == "MESSAGE") {
displayMessage(e.attributes.user, e.attributes.text);
}*/
trace(""+String(doc));
};
//
var my_xml:XML = new XML();
var myLogin:XMLNode = my_xml.createElement("login");
myLogin.attributes.username = "hehe";
myLogin.attributes.password = "1234";
my_xml.appendChild(myLogin);
socket.send(my_xml);