Source code: com/act365/net/udp/UDPWriter.java
1 /*
2 * JSocket Wrench
3 *
4 * Copyright (C) act365.com October 2003
5 *
6 * Web site: http://www.act365.com/wrench
7 * E-mail: developers@act365.com
8 *
9 * The JSocket Wrench library adds support for low-level Internet protocols
10 * to the Java programming language.
11 *
12 * This program is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU General Public License as published by the Free
14 * Software Foundation; either version 2 of the License, or (at your option)
15 * any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
20 * Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License along with
23 * this program; if not, write to the Free Software Foundation, Inc.,
24 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 */
26
27 package com.act365.net.udp ;
28
29 import com.act365.net.*;
30
31 /**
32 * Class <code>UDPWriter</code> writes UDP messages into bytestreams.
33 */
34
35 public class UDPWriter {
36
37 static byte[] write( UDPMessage message ){
38
39 byte[] buffer = new byte[ message.length ];
40
41 SocketUtils.shortToBytes( message.sourceport , buffer , 0 );
42 SocketUtils.shortToBytes( message.destinationport , buffer , 2 );
43 SocketUtils.shortToBytes( message.length , buffer , 4 );
44 SocketUtils.shortToBytes( message.checksum , buffer , 6 );
45
46 int i = 7 ;
47
48 while( ++ i < buffer.length ){
49 buffer[ i ] = message.data[ i - 8 ];
50 }
51
52 return buffer ;
53 }
54
55 /**
56 * Builds a UDP message and writes it to a bytestream.
57 */
58
59 public static byte[] write( byte[] sourceaddress ,
60 short sourceport ,
61 byte[] destinationaddress ,
62 short destinationport ,
63 byte[] data ,
64 int datalength ) {
65
66 UDPMessage message = new UDPMessage();
67
68 message.sourceport = sourceport ;
69 message.destinationport = destinationport ;
70 message.length = (short)( datalength + 8 );
71 message.checksum = 0 ;
72 message.data = data ;
73
74 message.checksum = SocketUtils.checksum( sourceaddress ,
75 destinationaddress ,
76 (byte) SocketConstants.IPPROTO_UDP ,
77 message.length ,
78 write( message ) ,
79 (int) 0 );
80
81 return write( message );
82 }
83 }
84