1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 1997-2004 Apple Computer, Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
20 using System.Collections;
21 using System.ComponentModel;
22 using System.Windows.Forms;
24 using System.Net.Sockets;
29 namespace SimpleChat.NET
32 /// Summary description for Form1.
36 public class SimpleChat : System.Windows.Forms.Form
38 private System.Windows.Forms.ComboBox comboBox1;
39 private System.Windows.Forms.TextBox textBox2;
40 private System.Windows.Forms.Button button1;
41 private System.Windows.Forms.Label label1;
43 private Bonjour.DNSSDEventManager m_eventManager = null;
45 private Bonjour.DNSSDService m_service = null;
47 private Bonjour.DNSSDService m_registrar = null;
49 private Bonjour.DNSSDService m_browser = null;
51 private Bonjour.DNSSDService m_resolver = null;
52 private String m_name;
54 private Socket m_socket = null;
56 private const int BUFFER_SIZE = 1024;
58 public byte[] m_buffer = new byte[BUFFER_SIZE];
60 public bool m_complete = false;
62 public StringBuilder m_sb = new StringBuilder();
64 delegate void ReadMessageCallback(String data);
66 ReadMessageCallback m_readMessageCallback;
68 /// Required designer variable.
70 private System.ComponentModel.Container components = null;
71 private System.Windows.Forms.RichTextBox richTextBox1;
75 // Called by DNSServices core as a result of Register()
109 m_browser = m_service.Browse(0, 0, "_p2pchat._udp", null, m_eventManager);
117 MessageBox.Show("Browse Failed", "Error");
128 // Called by DNSServices core as a result of a Browse call
143 if (serviceName != m_name)
147 PeerData peer = new PeerData();
151 peer.InterfaceIndex = ifIndex;
153 peer.Name = serviceName;
157 peer.Domain = domain;
163 comboBox1.Items.Add(peer);
167 if (comboBox1.Items.Count == 1)
171 comboBox1.SelectedIndex = 0;
186 // Called by DNSServices core as a result of a Browse call
214 PeerData peer = new PeerData();
218 peer.InterfaceIndex = ifIndex;
220 peer.Name = serviceName;
224 peer.Domain = domain;
230 comboBox1.Items.Remove(peer);
237 // Called by DNSServices core as a result of DNSService.Resolve()
271 PeerData peer = (PeerData)comboBox1.SelectedItem;
283 m_resolver = m_service.QueryRecord(0, ifIndex, hostName, DNSSDRRType.kDNSSDType_A, DNSSDRRClass.kDNSSDClass_IN, m_eventManager );
291 MessageBox.Show("QueryRecord Failed", "Error");
301 // Called by DNSServices core as a result of DNSService.QueryRecord()
308 DNSSDService service,
313 DNSSDRRClass rrclass,
325 PeerData peer = (PeerData) comboBox1.SelectedItem;
328 uint bits = BitConverter.ToUInt32( (Byte[])rdata, 0);
329 System.Net.IPAddress address = new System.Net.IPAddress(bits);
331 peer.Address = address;
342 DNSSDService service,
350 MessageBox.Show("Operation returned an error code " + error, "Error");
362 // Called when there is data to be read on a socket
366 // This is called (indirectly) from OnReadSocket()
386 for (int i = 0; i < msg.Length && msg[i] != ':'; i++)
390 rgb = rgb ^ ((int)msg[i] << (i % 3 + 2) * 8);
396 Color color = Color.FromArgb(rgb & 0x007F7FFF);
398 richTextBox1.SelectionColor = color;
400 richTextBox1.AppendText(msg + Environment.NewLine);
407 // Called by the .NET core when there is data to be read on a socket
409 // This is called from a worker thread by the .NET core
419 int read = m_socket.EndReceive(ar);
423 String msg = Encoding.UTF8.GetString(m_buffer, 0, read);
424 Invoke(m_readMessageCallback, new Object[]{msg});
427 m_socket.BeginReceive(m_buffer, 0, BUFFER_SIZE, 0, new AsyncCallback(OnReadSocket), this);
438 // Required for Windows Form Designer support
440 InitializeComponent();
448 m_service = new DNSSDService();
456 MessageBox.Show("Bonjour Service is not available", "Error");
464 m_eventManager = new DNSSDEventManager();
466 m_eventManager.ServiceRegistered += new _IDNSSDEvents_ServiceRegisteredEventHandler(this.ServiceRegistered);
468 m_eventManager.ServiceFound += new _IDNSSDEvents_ServiceFoundEventHandler(this.ServiceFound);
470 m_eventManager.ServiceLost += new _IDNSSDEvents_ServiceLostEventHandler(this.ServiceLost);
472 m_eventManager.ServiceResolved += new _IDNSSDEvents_ServiceResolvedEventHandler(this.ServiceResolved);
474 m_eventManager.QueryRecordAnswered += new _IDNSSDEvents_QueryRecordAnsweredEventHandler(this.QueryAnswered);
476 m_eventManager.OperationFailed += new _IDNSSDEvents_OperationFailedEventHandler(this.OperationFailed);
478 m_readMessageCallback = new ReadMessageCallback(OnReadMessage);
480 this.Load += new System.EventHandler(this.Form1_Load);
482 this.AcceptButton = button1;
486 /// Clean up any resources being used.
488 protected override void
489 Dispose( bool disposing )
493 if (components != null)
495 components.Dispose();
498 if (m_registrar != null)
503 if (m_browser != null)
510 if (m_resolver != null)
520 m_eventManager.ServiceFound -= new _IDNSSDEvents_ServiceFoundEventHandler(this.ServiceFound);
522 m_eventManager.ServiceLost -= new _IDNSSDEvents_ServiceLostEventHandler(this.ServiceLost);
524 m_eventManager.ServiceResolved -= new _IDNSSDEvents_ServiceResolvedEventHandler(this.ServiceResolved);
526 m_eventManager.QueryRecordAnswered -= new _IDNSSDEvents_QueryRecordAnsweredEventHandler(this.QueryAnswered);
528 m_eventManager.OperationFailed -= new _IDNSSDEvents_OperationFailedEventHandler(this.OperationFailed);
530 base.Dispose( disposing );
533 #region Windows Form Designer generated code
535 /// Required method for Designer support - do not modify
536 /// the contents of this method with the code editor.
538 private void InitializeComponent()
540 this.comboBox1 = new System.Windows.Forms.ComboBox();
541 this.textBox2 = new System.Windows.Forms.TextBox();
542 this.button1 = new System.Windows.Forms.Button();
543 this.label1 = new System.Windows.Forms.Label();
544 this.richTextBox1 = new System.Windows.Forms.RichTextBox();
545 this.SuspendLayout();
549 this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
550 | System.Windows.Forms.AnchorStyles.Right);
551 this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
552 this.comboBox1.Location = new System.Drawing.Point(59, 208);
553 this.comboBox1.Name = "comboBox1";
554 this.comboBox1.Size = new System.Drawing.Size(224, 21);
555 this.comboBox1.Sorted = true;
556 this.comboBox1.TabIndex = 5;
557 this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
561 this.textBox2.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
562 | System.Windows.Forms.AnchorStyles.Right);
563 this.textBox2.Location = new System.Drawing.Point(8, 248);
564 this.textBox2.Name = "textBox2";
565 this.textBox2.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal;
566 this.textBox2.Size = new System.Drawing.Size(192, 20);
567 this.textBox2.TabIndex = 2;
568 this.textBox2.Text = "";
569 this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged);
573 this.button1.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
574 this.button1.Enabled = false;
575 this.button1.Location = new System.Drawing.Point(208, 248);
576 this.button1.Name = "button1";
577 this.button1.TabIndex = 3;
578 this.button1.Text = "Send";
579 this.button1.Click += new System.EventHandler(this.button1_Click);
583 this.label1.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left);
584 this.label1.Location = new System.Drawing.Point(8, 210);
585 this.label1.Name = "label1";
586 this.label1.Size = new System.Drawing.Size(48, 16);
587 this.label1.TabIndex = 4;
588 this.label1.Text = "Talk To:";
592 this.richTextBox1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
593 | System.Windows.Forms.AnchorStyles.Left)
594 | System.Windows.Forms.AnchorStyles.Right);
595 this.richTextBox1.Location = new System.Drawing.Point(8, 8);
596 this.richTextBox1.Name = "richTextBox1";
597 this.richTextBox1.ReadOnly = true;
598 this.richTextBox1.Size = new System.Drawing.Size(272, 184);
599 this.richTextBox1.TabIndex = 1;
600 this.richTextBox1.Text = "";
604 this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
605 this.ClientSize = new System.Drawing.Size(292, 273);
606 this.Controls.AddRange(new System.Windows.Forms.Control[] {
613 this.Text = "SimpleChat.NET";
614 this.ResumeLayout(false);
619 private void Form1_Load(object sender, EventArgs e)
621 IPEndPoint localEP = new IPEndPoint(System.Net.IPAddress.Any, 0);
624 // create the socket and bind to INADDR_ANY
626 m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
627 m_socket.Bind(localEP);
628 localEP = (IPEndPoint) m_socket.LocalEndPoint;
631 // start asynchronous read
633 m_socket.BeginReceive(m_buffer, 0, BUFFER_SIZE, 0, new AsyncCallback(this.OnReadSocket), this);
638 // start the register and browse operations
640 m_registrar = m_service.Register( 0, 0, System.Environment.UserName, "_p2pchat._udp", null, null, ( ushort ) localEP.Port, null, m_eventManager );
644 MessageBox.Show("Bonjour service is not available", "Error");
650 /// The main entry point for the application.
655 Application.Run(new SimpleChat());
659 // send the message to a peer
661 private void button1_Click(object sender, System.EventArgs e)
663 PeerData peer = (PeerData) comboBox1.SelectedItem;
665 String message = m_name + ": " + textBox2.Text;
667 Byte[] bytes = Encoding.UTF8.GetBytes(message);
669 IPEndPoint endPoint = new IPEndPoint( peer.Address, peer.Port );
673 m_socket.SendTo(bytes, endPoint);
675 richTextBox1.SelectionColor = Color.Black;
677 richTextBox1.AppendText(textBox2.Text + "\n");
683 // called when typing in message box
685 private void textBox2_TextChanged(object sender, System.EventArgs e)
687 PeerData peer = (PeerData) comboBox1.SelectedItem;
688 button1.Enabled = ((peer.Address != null) && (textBox2.Text.Length > 0));
692 // called when peer target changes
696 /// <param name="sender"></param>
697 /// <param name="e"></param>
698 private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
700 PeerData peer = (PeerData) comboBox1.SelectedItem;
704 m_resolver = m_service.Resolve(0, peer.InterfaceIndex, peer.Name, peer.Type, peer.Domain, m_eventManager);
708 MessageBox.Show("Unable to Resolve service", "Error");
722 // Holds onto the information associated with a peer on the network
726 public class PeerData
730 public uint InterfaceIndex;
736 public String Domain;
738 public IPAddress Address;
744 public override String
770 if ((object)this == other)
778 else if (other is PeerData)
782 PeerData otherPeerData = (PeerData)other;
786 result = (this.Name == otherPeerData.Name);
806 return Name.GetHashCode();