home *** CD-ROM | disk | FTP | other *** search
/ Late Night VRML 2.0 with Java CD-ROM / code.zip / Ch18 / multi / TextSender.java < prev    next >
Encoding:
Java Source  |  1997-02-21  |  1.9 KB  |  62 lines

  1. // An object that sends text messages
  2.  
  3. // Written by Bernie Roehl, January 1997
  4.  
  5. package multi;
  6.  
  7. import java.net.*;
  8. import java.io.*;
  9.  
  10. public class TextSender {
  11.  
  12.     InetAddress host;
  13.     int port;
  14.     int text_ssrc;
  15.     int seqnum = 0;
  16.  
  17.     DatagramSocket socket;
  18.     DatagramPacket packet;
  19.  
  20.     ByteArrayOutputStream bout;
  21.     DataOutputStream dout;
  22.  
  23.     public synchronized int getTextId() { return text_ssrc; }
  24.     public synchronized void setTextId(int id) { text_ssrc = id; }
  25.  
  26.     public TextSender(String hostname, int prt) throws SocketException {
  27.         try { host = InetAddress.getByName(hostname); }
  28.         catch (UnknownHostException ex) {
  29.             System.out.println("Unknown host \"" + hostname + "\"");
  30.             return;
  31.         }      
  32.         port = prt;
  33.         bout = new ByteArrayOutputStream();
  34.         dout = new DataOutputStream(bout);
  35.         socket = new DatagramSocket();
  36.     }
  37.  
  38.     public synchronized void sendText(String text) throws IOException {
  39.         int msglen = text.length();
  40. System.out.println("In TextSender, length = " + msglen);
  41.         byte[] message = new byte[msglen];
  42.         text.getBytes(0, msglen, message, 0);
  43.         bout.reset();
  44.         // version = 2, padding = 0, extension = 0, CSRC count = 0
  45.         dout.writeByte(0x80);
  46.         dout.writeByte(80);    // mark = 0, payload type = 80
  47.         dout.writeShort(seqnum++);    // sequence number
  48.         dout.writeInt(0);      // timestamp
  49.         dout.writeInt(text_ssrc);     // entid
  50.         dout.writeShort(0);    // type
  51.         dout.writeShort((short) msglen);
  52.         dout.write(message, 0, msglen);
  53.         dout.flush();
  54. System.out.println("In TextSender, byte array length = " + bout.size());
  55.         packet = new DatagramPacket(bout.toByteArray(), bout.size(), host, port);
  56.         socket.send(packet);
  57. System.out.println("In TextSender, packet size = " + packet.getLength());
  58.     }
  59.  
  60. }
  61.  
  62.