日期:2014-05-18 浏览次数:20894 次
public void StartListening(string ip) { serverSK = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip), 9095); try { allDone.Reset(); serverSK.BeginAccept(new AsyncCallback(AcceptCallback), serverSK); allDone.WaitOne(); } catch { } } public void AcceptCallback(IAsyncResult ar) { try { allDone.Set(); Socket listener = ar.AsyncState as Socket; Socket handler = listener.EndAccept(ar); listener.BeginAccept(new AsyncCallback(AcceptCallback), handler); byte[] buffer = new byte[1024]; SocketHelper helper = new SocketHelper(buffer, handler); handler.BeginReceive(buffer, 0, 1, SocketFlags.None, new AsyncCallback(Receive), helper); } catch { // } } void Receive(IAsyncResult ia) { SocketHelper helper = ia.AsyncState as SocketHelper; Socket worker = helper.s; worker.EndReceive(ia); byte[] buffer = new byte[worker.Available + 1]; worker.Receive(buffer, 1, buffer.Length - 1, SocketFlags.None); buffer[0] = helper.b[0]; this.sendBackSocket = worker; //调用事件 this.OnMessageArrival(new AsyncEventArgs(buffer)); worker.BeginReceive(helper.b, 0, 1, SocketFlags.None, new AsyncCallback(Receive), helper); } /// <summary> /// 触发消息抵达事件 /// </summary> /// <param name="e">收到的字节数组</param> private void OnMessageArrival(AsyncEventArgs e) { if (this.receiveEventHandler != null) { this.receiveEventHandler(this, e); } }
/// <summary> /// 触发消息抵达事件 /// </summary> /// <param name="e">收到的字节数组</param> private void OnMessageArrival(AsyncEventArgs e) { if (this.receiveEventHandler != null) { this.text.BeginInvoke(new AsyncCallback(setText),Encoding.UTF8.GetString((byte[])e)); this.receiveEventHandler(this, e); } } public void setText(IAsyncResult ia) { }