日期:2014-05-18 浏览次数:20854 次
public static StateObject state; public static IPAddress ipAddress = IPAddress.Parse("0.0.0.0"); public static IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 2012); public static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { serverSocket.Bind(localEndPoint); serverSocket.Listen(100); serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket); MyFlowForm = new FlowMon(); Application.Run(MyFlowForm); } public static void AcceptCallback(IAsyncResult ar) { Socket serverSocket = (Socket)ar.AsyncState; Socket clientSocket = serverSocket.EndAccept(ar); state = new StateObject(); state.workSocket = clientSocket; Send("连接服务器成功"); clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } public static void ReadCallback(IAsyncResult ar) { StateObject state = (StateObject)ar.AsyncState; Socket clientSocket = state.workSocket; int bytesRead = clientSocket.EndReceive(ar); if (bytesRead > 0) { String str = Encoding.Unicode.GetString(state.buffer, 0, bytesRead); } clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } private static void Send(String data) { byte[] byteData = Encoding.Unicode.GetBytes(data); state.workSocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), state); } private static void SendCallback(IAsyncResult ar) { try { Socket clientSocket = (Socket)ar.AsyncState; int bytesSent = clientSocket.EndSend(ar); } catch (Exception e) { Console.WriteLine(e.ToString()); } } public class StateObject { public Socket workSocket = null; public const int BufferSize = 1024; public byte[] buffer = new byte[BufferSize]; }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Windows.Forms; using System.Threading; namespace Flowfairy { class FlowSocket { public StateObject state; public IPAddress ipAddress; public IPEndPoint localEndPoint; public Socket serverSocket; public void ListenFlow() { ipAddress = IPAddress.Parse("0.0.0.0"); localEndPoint = new IPEndPoint(ipAddress, 2012); this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立socket serverSocket.Bind(localEndPoint);//将套接字绑定到用于TCP通信的本地0.0.0.0地址和2012端口上 serverSocket.Listen(100);//设置套接字处于监听状态 serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket); //开始接受新连接,获取将处理链接的serverSocket,并将Socket提交给将处理请求的AcceptCallback线程{ } public void AcceptCallback(IAsyncResult ar)//启动异步接收数据 { try { Socket serverSocket = (Socket)ar.AsyncState; Socket clientSocket = serverSocket.EndAccept(ar);