private void Form1_Load(object sender, EventArgs e) { IPEndPoint localEP = new IPEndPoint(System.Net.IPAddress.Any, 0); // // create the socket and bind to INADDR_ANY // socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(localEP); localEP = (IPEndPoint)socket.LocalEndPoint; // // start asynchronous read // SocketStateObject so = new SocketStateObject(socket); socket.BeginReceive(so.m_buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(this.OnReadSocket), so); try { // // start the register and browse operations // registrar = DNSService.Register(0, 0, System.Environment.UserName, "_p2pchat._udp", null, null, localEP.Port, null, new DNSService.RegisterReply(OnRegisterReply)); browser = DNSService.Browse(0, 0, "_p2pchat._udp", null, new DNSService.BrowseReply(OnBrowseReply)); } catch { MessageBox.Show("DNSServices Not Available", "Error"); Application.Exit(); } }
OnReadSocket ( IAsyncResult ar ) { SocketStateObject so = (SocketStateObject)ar.AsyncState; Socket s = so.WorkSocket; try { if (s == null) { return; } int read = s.EndReceive(ar); if (read > 0) { String msg = Encoding.UTF8.GetString(so.m_buffer, 0, read); Invoke(readMessageCallback, new Object[] { msg }); } s.BeginReceive(so.m_buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(OnReadSocket), so); } catch { } }
private void Form1_Load(object sender, EventArgs e) { IPEndPoint localEP = new IPEndPoint(System.Net.IPAddress.Any, 0); // // create the socket and bind to INADDR_ANY // socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(localEP); localEP = (IPEndPoint) socket.LocalEndPoint; // // start asynchronous read // SocketStateObject so = new SocketStateObject(socket); socket.BeginReceive(so.m_buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(this.OnReadSocket), so); try { // // start the register and browse operations // registrar = DNSService.Register(0, 0, System.Environment.UserName, "_p2pchat._udp", null, null, localEP.Port, null, new DNSService.RegisterReply(OnRegisterReply)); browser = DNSService.Browse(0, 0, "_p2pchat._udp", null, new DNSService.BrowseReply(OnBrowseReply)); } catch { MessageBox.Show("DNSServices Not Available", "Error"); Application.Exit(); } }