summaryrefslogtreecommitdiffstats
path: root/mDNSResponder/Clients/Java/SimpleChat.java
blob: a1fee5c018ead48351b4e9ee94d53bf6a9d3e8e1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/* -*- Mode: Java; tab-width: 4 -*-
 *
 * Copyright (c) 2004 Apple Computer, Inc. All rights reserved.
 *
 * Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
 * ("Apple") in consideration of your agreement to the following terms, and your
 * use, installation, modification or redistribution of this Apple software
 * constitutes acceptance of these terms.  If you do not agree with these terms,
 * please do not use, install, modify or redistribute this Apple software.
 *
 * In consideration of your agreement to abide by the following terms, and subject
 * to these terms, Apple grants you a personal, non-exclusive license, under Apple's
 * copyrights in this original Apple software (the "Apple Software"), to use,
 * reproduce, modify and redistribute the Apple Software, with or without
 * modifications, in source and/or binary forms; provided that if you redistribute
 * the Apple Software in its entirety and without modifications, you must retain
 * this notice and the following text and disclaimers in all such redistributions of
 * the Apple Software.  Neither the name, trademarks, service marks or logos of
 * Apple Computer, Inc. may be used to endorse or promote products derived from the
 * Apple Software without specific prior written permission from Apple.  Except as
 * expressly stated in this notice, no other rights or licenses, express or implied,
 * are granted by Apple herein, including but not limited to any patent rights that
 * may be infringed by your derivative works or by other works in which the Apple
 * Software may be incorporated.
 *
 * The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
 * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
 * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
 * COMBINATION WITH YOUR PRODUCTS.
 *
 * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
 * OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
 * (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	SimpleChat is a simple peer-to-peer chat program that demonstrates 
	DNS-SD registration, browsing, resolving and record-querying.

	To do:
	- implement better coloring algorithm
 */


import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

import com.apple.dnssd.*;


class	SimpleChat implements	ResolveListener, RegisterListener, QueryListener, 
								ActionListener, ItemListener, Runnable
{
	Document			textDoc;			// Holds all the chat text
	JTextField			inputField;			// Holds a pending chat response
	String				ourName;			// name used to identify this user in chat
	DNSSDService		browser;			// object that actively browses for other chat clients
	DNSSDService		resolver;			// object that resolves other chat clients
	DNSSDRegistration	registration;		// object that maintains our connection advertisement
	JComboBox			targetPicker;		// Indicates who we're talking to
	TargetListModel		targetList;			// and its list model
	JButton				sendButton;			// Will send text in inputField to target
	InetAddress			buddyAddr;			// and address
	int					buddyPort;			// and port
	DatagramPacket		dataPacket;			// Inbound data packet
	DatagramSocket		outSocket;			// Outbound data socket
	SimpleAttributeSet	textAttribs;

	static final String	kChatExampleRegType = "_p2pchat._udp";
	static final String	kWireCharSet = "ISO-8859-1";

	public		SimpleChat() throws Exception
	{
		JFrame frame = new JFrame("SimpleChat");
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {System.exit(0);}
		});

    	ourName = System.getProperty( "user.name");
		targetList = new TargetListModel();
		textAttribs = new SimpleAttributeSet();
		DatagramSocket inSocket = new DatagramSocket();
		dataPacket = new DatagramPacket( new byte[ 4096], 4096);
		outSocket = new DatagramSocket();

		this.setupSubPanes( frame.getContentPane(), frame.getRootPane());
		frame.pack();
		frame.setVisible(true);
		inputField.requestFocusInWindow();

		browser = DNSSD.browse( 0, 0, kChatExampleRegType, "", new SwingBrowseListener( targetList));

		registration = DNSSD.register( 0, 0, ourName, kChatExampleRegType, "", "", inSocket.getLocalPort(), null, this);

		new ListenerThread( this, inSocket, dataPacket).start();
	}

	protected void	setupSubPanes( Container parent, JRootPane rootPane)
	{	
		parent.setLayout( new BoxLayout( parent, BoxLayout.Y_AXIS));

		JPanel textRow = new JPanel();
		textRow.setLayout( new BoxLayout( textRow, BoxLayout.X_AXIS));
		textRow.add( Box.createRigidArea( new Dimension( 16, 0)));
		JEditorPane textPane = new JEditorPane( "text/html", "<BR>");
		textPane.setPreferredSize( new Dimension( 400, 300));
		textPane.setEditable( false);
		JScrollPane textScroller = new JScrollPane( textPane);
		textRow.add( textScroller);
		textRow.add( Box.createRigidArea( new Dimension( 16, 0)));
		textDoc = textPane.getDocument();

		JPanel addressRow = new JPanel();
		addressRow.setLayout( new BoxLayout( addressRow, BoxLayout.X_AXIS));
		targetPicker = new JComboBox( targetList);
		targetPicker.addItemListener( this);
		addressRow.add( Box.createRigidArea( new Dimension( 16, 0)));
		addressRow.add( new JLabel( "Talk to: "));
		addressRow.add( targetPicker);
		addressRow.add( Box.createHorizontalGlue());

		JPanel buttonRow = new JPanel();
		buttonRow.setLayout( new BoxLayout( buttonRow, BoxLayout.X_AXIS));
		buttonRow.add( Box.createRigidArea( new Dimension( 16, 0)));
		inputField = new JTextField();
		// prevent inputField from hijacking <Enter> key
		inputField.getKeymap().removeKeyStrokeBinding( KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, 0));
		buttonRow.add( inputField);
		sendButton = new JButton( "Send");
		buttonRow.add( Box.createRigidArea( new Dimension( 8, 0)));
		buttonRow.add( sendButton);
		buttonRow.add( Box.createRigidArea( new Dimension( 16, 0)));
		rootPane.setDefaultButton( sendButton);
		sendButton.addActionListener( this);
		sendButton.setEnabled( false);

		parent.add( Box.createRigidArea( new Dimension( 0, 16)));
		parent.add( textRow);
		parent.add( Box.createRigidArea( new Dimension( 0, 8)));
		parent.add( addressRow);
		parent.add( Box.createRigidArea( new Dimension( 0, 8)));
		parent.add( buttonRow);
		parent.add( Box.createRigidArea( new Dimension( 0, 16)));
	}

	public void	serviceRegistered( DNSSDRegistration registration, int flags, 
									String serviceName, String regType, String domain)
	{
		ourName = serviceName;		// might have been renamed on collision
	}

	public void	operationFailed( DNSSDService service, int errorCode)
	{
		System.out.println( "Service reported error " + String.valueOf( errorCode));
	}

	public void	serviceResolved( DNSSDService resolver, int flags, int ifIndex, String fullName, 
										String hostName, int port, TXTRecord txtRecord)
	{
		buddyPort = port;
		try {
			// Start a record query to obtain IP address from hostname
			DNSSD.queryRecord( 0, ifIndex, hostName, 1 /* ns_t_a */, 1 /* ns_c_in */, 
								new SwingQueryListener( this));
		}
		catch ( Exception e) { terminateWithException( e); }
		resolver.stop();
	}

	public void	queryAnswered( DNSSDService query, int flags, int ifIndex, String fullName, 
									int rrtype, int rrclass, byte[] rdata, int ttl)
	{
		try {
			buddyAddr = InetAddress.getByAddress( rdata);
		}
		catch ( Exception e) { terminateWithException( e); }
		sendButton.setEnabled( true);
	}

	public void		actionPerformed( ActionEvent e) 	// invoked when Send button is hit
	{
		try
		{
			String	sendString = ourName + ": " + inputField.getText();
			byte[] sendData = sendString.getBytes( kWireCharSet);
			outSocket.send( new DatagramPacket( sendData, sendData.length, buddyAddr, buddyPort));
			StyleConstants.setForeground( textAttribs, Color.black);
			textDoc.insertString( textDoc.getLength(), inputField.getText() + "\n", textAttribs);
			inputField.setText( "");
		}
		catch ( Exception exception) { terminateWithException( exception); }
	}

	public void		itemStateChanged( ItemEvent e) 	// invoked when Target selection changes
	{
		sendButton.setEnabled( false);
		if ( e.getStateChange() == ItemEvent.SELECTED)
		{
			try {
				TargetListElem	sel = (TargetListElem) targetList.getSelectedItem();
				resolver = DNSSD.resolve( 0, sel.fInt, sel.fServiceName, sel.fType, sel.fDomain, this);
			}
			catch ( Exception exception) { terminateWithException( exception); }
		}
	}

	public void		run()		// invoked on event thread when inbound packet arrives
	{
		try
		{
			String	inMessage = new String( dataPacket.getData(), 0, dataPacket.getLength(), kWireCharSet);
			StyleConstants.setForeground( textAttribs, this.getColorFor( dataPacket.getData(), dataPacket.getLength()));
			textDoc.insertString( textDoc.getLength(), inMessage + "\n", textAttribs);
		}
		catch ( Exception e) { terminateWithException( e); }
	}

	protected Color		getColorFor( byte[] chars, int length)
	// Produce a mapping from a string to a color, suitable for text display
	{
		int		rgb = 0;
		for ( int i=0; i < length && chars[i] != ':'; i++)
			rgb = rgb ^ ( (int) chars[i] << (i%3+2) * 8);
		return new Color( rgb & 0x007F7FFF);	// mask off high bits so it is a dark color
		
//		for ( int i=0; i < length && chars[i] != ':'; i++)
		
	}

	protected static void	terminateWithException( Exception e)
	{
		e.printStackTrace();
		System.exit( -1);
	}

    public static void main(String s[]) 
    {
    	try {
			new SimpleChat();
		}
		catch ( Exception e) { terminateWithException( e); }
    }
}



class	TargetListElem
{
	public	TargetListElem( String serviceName, String domain, String type, int ifIndex)
	{ fServiceName = serviceName; fDomain = domain; fType = type; fInt = ifIndex; }
	
	public String	toString() { return fServiceName; }
	
	public String	fServiceName, fDomain, fType;
	public int		fInt;
}

class		TargetListModel extends DefaultComboBoxModel implements BrowseListener
{
	/* The Browser invokes this callback when a service is discovered. */
	public void	serviceFound( DNSSDService browser, int flags, int ifIndex, 
							String serviceName, String regType, String domain)
	{
		TargetListElem		match = this.findMatching( serviceName);	// probably doesn't handle near-duplicates well.

		if ( match == null)
			this.addElement( new TargetListElem( serviceName, domain, regType, ifIndex));
	}

	/* The Browser invokes this callback when a service disappears. */
	public void	serviceLost( DNSSDService browser, int flags, int ifIndex, 
							String serviceName, String regType, String domain)
	{
		TargetListElem		match = this.findMatching( serviceName);	// probably doesn't handle near-duplicates well.

		if ( match != null)
			this.removeElement( match);
	}

	/* The Browser invokes this callback when a service disappears. */
	public void	operationFailed( DNSSDService service, int errorCode)
	{
		System.out.println( "Service reported error " + String.valueOf( errorCode));
	}

	protected TargetListElem	findMatching( String match)
	{
		for ( int i = 0; i < this.getSize(); i++)
			if ( match.equals( this.getElementAt( i).toString()))
				return (TargetListElem) this.getElementAt( i);
		return null;
	}

}


// A ListenerThread runs its owner when datagram packet p appears on socket s.
class	ListenerThread extends Thread
{
	public			ListenerThread( Runnable owner, DatagramSocket s, DatagramPacket p) 
	{ fOwner = owner; fSocket = s; fPacket = p; }

	public void		run()
	{		
		while ( true )
		{
			try 
			{
				fSocket.receive( fPacket);
				SwingUtilities.invokeAndWait( fOwner);	// process data on main thread
			}
			catch( Exception e)
			{
				break;	// terminate thread
			}
		}
	}

	protected Runnable			fOwner;
	protected DatagramSocket	fSocket;
	protected DatagramPacket	fPacket;
}