Preparing a chat program
I am preparing a chat program which should display the messeges received from the server and from the user in diffrent color. I know it can be done with JTextPane. But I am not able to do it. can anyone tell me how to do with a small example. thanks,
hope this helps
http://developer.java.sun.com/developer/onlineTraining/GUI/Swing2/shortcourse.html
hf,
dani
Similar Messages
-
Hi,
The problem I am having is when checking to see if two specific users are using the chat program as I want them to have a separate multicast session. The if statements work and the client sends the message. The server just doesn't seem to relay it back to the client in either case.
The code for the client part is below:
if (userName.startsWith ("Steve") || userName.startsWith ("David"))
MulticastSocket socket = new MulticastSocket (4447);
InetAddress address = InetAddress.getByName ("233.0.0.13");
socket.joinGroup (address);
else
MulticastSocket socket = new MulticastSocket (4449);
InetAddress address = InetAddress.getByName ("232.0.0.13");
socket.joinGroup (address);
And the server part:
if (received.startsWith ("Steve") || received.startsWith ("David"))
InetAddress group = InetAddress.getByName ("233.0.0.13");
packet = new DatagramPacket (buf, buf.length, group, 4447);
socket.send (packet);
else
InetAddress group = InetAddress.getByName ("232.0.0.13");
packet = new DatagramPacket (buf, buf.length, group, 4449);
socket.send (packet);
Does anyone have any ideas??Chat Client Full Code
public class MulticastChatClient extends MulticastChatClientGUI
public ButtonHandler bHandler;
DatagramSocket socket;
String ipAddress;
String userName;
String passWord;
String msgToBuf;
String logMsg= "";
String checkBye;
Boolean authenticatedUser;
String deNullString (String s)
//Function to get rid of garbage at the end of the buffer prior to
//displaying it on the screen and saving to file.
String result = "";
int i = 0;
while (s.charAt(i) != '\0')
result = result + s.charAt(i);
i ++;
return result;
public MulticastChatClient (String title)
super (title);
bHandler = new ButtonHandler();
sendButton.addActionListener( bHandler );
try
socket = new DatagramSocket ();
catch (IOException e)
private class ButtonHandler implements ActionListener
public void actionPerformed (ActionEvent event) //throws IOException
// Get a datagram socket
try
byte[] buf = new byte[128];
InetAddress address = InetAddress.getByName (ipAddress);
//Put username before the message the user sends
msgToBuf=userName + " Says >> ";
//Populate buffer with text in the txArea
msgToBuf=msgToBuf + txArea.getText();
buf = msgToBuf.getBytes();
//Open up port 4448 and prepare to send the packet
DatagramPacket packet = new DatagramPacket (buf, buf.length, address, 4448);
System.out.println ("About to send packet");
//Send the packet to the server
socket.send(packet);
System.out.println ("Packet sent");
catch (IOException e)
//Error handling
System.err.println("Couldn't get I/O for the connection to the server");
System.exit(1);
public void run () throws IOException
//Welcome user, ask for their name
userName = JOptionPane.showInputDialog(null,"Please enter your name...",
"Welcome To Chat V1.0",JOptionPane.QUESTION_MESSAGE);
//Password verification
//Promt user to enter password
passWord = JOptionPane.showInputDialog(null,"Please enter password...",
"User Authentication",JOptionPane.QUESTION_MESSAGE);
if(passWord.equals ("letmein"))
//Correct password
authenticatedUser = true;
else
//Wrong password
authenticatedUser = false;
//Inform the user and close the application
JOptionPane.showMessageDialog(null, "Wrong Password, Chat program ended",
"Authenticaion Failure",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
//User To Enter IP Address
ipAddress = JOptionPane.showInputDialog(null, "Thanks " userName "... Please Enter Server IP",
"Connection Details",JOptionPane.QUESTION_MESSAGE);
// set up connection to multicast server
if (userName.startsWith ("Steve") || userName.startsWith ("David"))
MulticastSocket socket = new MulticastSocket (4447);
InetAddress address = InetAddress.getByName ("233.0.0.13");
socket.joinGroup (address);
else
MulticastSocket socket = new MulticastSocket (4449);
InetAddress address = InetAddress.getByName ("232.0.0.13");
socket.joinGroup (address);
while (true)
// send request
byte[] buf = new byte[128];
DatagramPacket packet = new DatagramPacket (buf, buf.length);
socket.receive (packet);
System.out.println ("Received packet");
// display response
String received = new String (packet.getData());
System.out.println ("Remote packet: " + received);
logMsg = logMsg + "\n" + deNullString (received);
checkBye = txArea.getText();
if (checkBye.equals ("Bye"))
try
//Create log file ClientMsg.log, outFile is used to operate on it
BufferedWriter outFile = new BufferedWriter (new FileWriter ("ClientMsg.log"));
outFile.write (logMsg);
outFile.close();
catch (IOException i){}
//Tell user the program is about to close
JOptionPane.showMessageDialog(null, "You terminated connection, Chat program ended",
"Session Info",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
rxArea.setText (rxArea.getText() + "\n" + deNullString (received));
Chat Server Full Code:
public class MulticastChatServer
public static void main(String[] args) throws java.io.IOException
//Open up socket and listen on port 4448
DatagramSocket socket = new DatagramSocket (4448);
DatagramPacket packet;
//Variable to hold all messages
String logMsg="";
System.out.println ("Starting Multicast Chat Server");
//Loop forever
while (true)
try
//Setup a 128 Byte array
byte[] buf = new byte[128];
// receive packet
packet = new DatagramPacket (buf, buf.length);
socket.receive (packet);
InetAddress address = packet.getAddress ();
int port = packet.getPort ();
//Convert buffer into a string
String received = new String (packet.getData());
//Add the IP address to the packet received
//received = "(" + address + ") " + received;
//Print received message on the console
System.out.println (received);
//Put the data into the buffer
buf = received.getBytes ();
//Write message to the message log variable
logMsg = logMsg + "\n" + received;
try
//Create log file ClientMsg.log, outFile is used to operate on it
BufferedWriter outFile = new BufferedWriter (new FileWriter ("ServerMsg.log"));
//Write the contents of logMsg to the file
outFile.write (logMsg);
//Close the file
outFile.close();
catch (IOException i){}
// multicast it
if (received.startsWith ("Steve") || received.startsWith ("David"))
System.out.println ("met");
InetAddress group = InetAddress.getByName ("233.0.0.13");
packet = new DatagramPacket (buf, buf.length, group, 4447);
socket.send (packet);
System.out.println ("met2");
else
InetAddress group = InetAddress.getByName ("232.0.0.13");
packet = new DatagramPacket (buf, buf.length, group, 4449);
socket.send (packet);
catch (IOException e)
e.printStackTrace();
} -
After a few days work, I have completed the mian voice chat program. I know there are so many people like me that wants that. I post these program. i will complete gui work later. and there is a problem in the program. if the speaking one do not speak for a while, the listening client will hear noise. Can some one help me.
package com.longshine.voice;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
// The ServerSocket we'll use for accepting new connections
private ServerSocket ss;
// A mapping from sockets to DataOutputStreams. This will
// help us avoid having to create a DataOutputStream each time
// we want to write to a stream.
private Hashtable outputStreams = new Hashtable();
final int bufSize = 16384;
//current speak_man
private int speakman=-1;
// Constructor and while-accept loop all in one.
public Server( int port ) throws IOException {
// All we have to do is listen
listen( port );
private void listen( int port ) throws IOException {
// Create the ServerSocket
ss = new ServerSocket( port );
// Tell the world we're ready to go
System.out.println( "Listening on "+ss );
// Keep accepting connections forever
while (true) {
// Grab the next incoming connection
Socket s = ss.accept();
// Tell the world we've got it
System.out.println( "Connection from "+s );
// Create a DataOutputStream for writing data to the
// other side
DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
// Save this stream so we don't need to make it again
outputStreams.put( s, dout );
// Create a new thread for this connection, and then forget
// about it
new VoiceServer( this, s );
// Get an enumeration of all the OutputStreams, one for each client
// connected to us
Enumeration getOutputStreams() {
return outputStreams.elements();
// Send a message to all clients (utility routine)
void sendToAll( byte[] voice ,Socket socket) {
// We synchronize on this because another thread might be
// calling removeConnection() and this would screw us up
// as we tried to walk through the list
synchronized( outputStreams ) {
// For each client ...
for (Enumeration e = outputStreams.keys(); e.hasMoreElements(); ) {
// ... get the output stream ...
Socket tmp=(Socket)e.nextElement();
if(!tmp.equals(socket))
try {
DataOutputStream dout = new DataOutputStream(tmp.getOutputStream());
// ... and send the message
dout.write(voice,0,44096);
dout.flush();
} catch( IOException ie ) { System.out.println( ie ); }
// Remove a socket, and it's corresponding output stream, from our
// list. This is usually called by a connection thread that has
// discovered that the connectin to the client is dead.
void removeConnection( Socket s ) {
// Synchronize so we don't mess up sendToAll() while it walks
// down the list of all output streamsa
synchronized( outputStreams ) {
// Tell the world
System.out.println( "Removing connection to "+s );
// Remove it from our hashtable/list
outputStreams.remove( s );
// Make sure it's closed
try {
s.close();
} catch( IOException ie ) {
System.out.println( "Error closing "+s );
ie.printStackTrace();
// Main routine
// Usage: java Server <port>
static public void main( String args[] ) throws Exception {
// Get the port # from the command line
int port = Integer.parseInt( args[0] );
// Create a Server object, which will automatically begin
// accepting connections.
new Server( port );
package com.longshine.voice;
import java.net.*;
import java.io.*;
import java.sql.*;
import java.io.*;
import java.net.*;
public class VoiceServer extends Thread
// The Server that spawned us
private Server server;
final int bufSize = 16384;
// The Socket connected to our client
private Socket socket;
// Constructor.
public VoiceServer( Server server, Socket socket ) {
// Save the parameters
this.server = server;
this.socket = socket;
// Start up the thread
start();
// This runs in a separate thread when start() is called in the
// constructor.
public void run() {
try {
// Create a DataInputStream for communication; the client
// is using a DataOutputStream to write to us
DataInputStream din = new DataInputStream( socket.getInputStream() );
byte[] voice=new byte[44096];
// Over and over, forever ...
while (true) {
// ... read the next message ...
// int bytes = din.read(voice,0,44096);
int bytes = din.read(voice);
// ... and have the server send it to all clients
server.sendToAll(voice,socket);
} catch( EOFException ie ) {
// This doesn't need an error message
} catch( IOException ie ) {
// This does; tell the world!
ie.printStackTrace();
} finally {
// The connection is closed for one reason or another,
// so have the server dealing with it
server.removeConnection( socket );
package com.longshine.voice;
import java.io.*;
import java.net.*;
public class Client {
private String host="";
private String port="";
private Socket socket;
private DataOutputStream dout;
private DataInputStream din;
private Capture capture=null;
private Play play=null;
public Client(String host,String port) {
this.host=host;
this.port=port;
public void init()
try
socket = new Socket( host, Integer.parseInt(port));
din = new DataInputStream( socket.getInputStream() );
dout = new DataOutputStream( socket.getOutputStream());
capture=new Capture(dout);
play=new Play(din);
catch(Exception e)
e.printStackTrace();
public static void main(String[] args) {
Client client = new Client("172.18.220.176","5678");
client.init();
if(args[0].equalsIgnoreCase("say"))
client.capture.start();
if(args[0].equalsIgnoreCase("hear"))
client.play.start();
package com.longshine.voice;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
import javax.sound.sampled.*;
import java.text.*;
import java.net.*;
public class Play implements Runnable {
SourceDataLine line;
Thread thread;
String errStr=null;
DataInputStream in=null;
AudioInputStream audioInputStream;
final int bufSize = 16384;
int duration=0;
public Play(DataInputStream in)
this.in=in;
public void start() {
errStr = null;
thread = new Thread(this);
thread.setName("Playback");
thread.start();
public void stop() {
thread = null;
private void shutDown(String message) {
if ((errStr = message) != null) {
System.err.println(errStr);
if (thread != null) {
thread = null;
public void createAudioInputStream() {
if (in != null ) {
try {
errStr = null;
java.io.BufferedInputStream oin = new java.io.BufferedInputStream(in);
audioInputStream = AudioSystem.getAudioInputStream(oin);
} catch (Exception ex) {
ex.printStackTrace();
} else {
public void run() {
// reload the file if loaded by file
if (in != null) {
// createAudioInputStream();
// make sure we have something to play
// if (audioInputStream == null) {
// shutDown("No loaded audio to play back");
// return;
// reset to the beginnning of the stream
// try {
// audioInputStream.reset();
// } catch (Exception e) {
// shutDown("Unable to reset the stream\n" + e);
// return;
// get an AudioInputStream of the desired format for playback
AudioFormat format = getFormat();
audioInputStream=new AudioInputStream(in, format, AudioSystem.NOT_SPECIFIED);
AudioInputStream playbackInputStream = AudioSystem.getAudioInputStream(format, audioInputStream);
if (playbackInputStream == null) {
shutDown("Unable to convert stream of format " + audioInputStream + " to format " + format);
return;
// define the required attributes for our line,
// and make sure a compatible line is supported.
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
format);
if (!AudioSystem.isLineSupported(info)) {
shutDown("Line matching " + info + " not supported.");
return;
// get and open the source data line for playback.
try {
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format, bufSize);
} catch (LineUnavailableException ex) {
shutDown("Unable to open the line: " + ex);
return;
// play back the captured audio data
int frameSizeInBytes = format.getFrameSize();
int bufferLengthInFrames = line.getBufferSize() / 8;
int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
byte[] data = new byte[bufferLengthInBytes];
int numBytesRead = 0;
// start the source data line
line.start();
while (thread != null) {
try {
if ((numBytesRead = playbackInputStream.read(data)) == -1) {
break;
int numBytesRemaining = numBytesRead;
while (numBytesRemaining > 0 ) {
numBytesRemaining -= line.write(data, 0, numBytesRemaining);
} catch (Exception e) {
shutDown("Error during playback: " + e);
break;
// we reached the end of the stream. let the data play out, then
// stop and close the line.
if (thread != null) {
line.drain();
line.stop();
line.close();
line = null;
shutDown(null);
public AudioFormat getFormat() {
AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
String encString = "linear";
float rate = Float.valueOf("44100").floatValue();
int sampleSize = 16;
String signedString = "signed";
boolean bigEndian = true;
int channels = 2;
if (encString.equals("linear")) {
if (signedString.equals("signed")) {
encoding = AudioFormat.Encoding.PCM_SIGNED;
} else {
encoding = AudioFormat.Encoding.PCM_UNSIGNED;
} else if (encString.equals("alaw")) {
encoding = AudioFormat.Encoding.ALAW;
return new AudioFormat(encoding, rate, sampleSize,
channels, (sampleSize/8)*channels, rate, bigEndian);
} // End class Playback
package com.longshine.voice;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
import javax.sound.sampled.*;
import java.text.*;
import java.net.*;
public class Capture implements Runnable {
TargetDataLine line;
Thread thread;
String errStr=null;
DataOutputStream out=null;
AudioInputStream audioInputStream;
final int bufSize = 16384;
int duration=0;
public Capture(DataOutputStream out)
this.out=out;
public void start() {
errStr = null;
thread = new Thread(this);
thread.setName("Playback");
thread.start();
public void stop() {
thread = null;
private void shutDown(String message) {
if ((errStr = message) != null) {
System.out.println(errStr);
if (thread != null) {
thread = null;
public AudioFormat getFormat() {
AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
String encString = "linear";
float rate = Float.valueOf("44100").floatValue();
int sampleSize = 16;
String signedString = "signed";
boolean bigEndian = true;
int channels = 2;
if (encString.equals("linear")) {
if (signedString.equals("signed")) {
encoding = AudioFormat.Encoding.PCM_SIGNED;
} else {
encoding = AudioFormat.Encoding.PCM_UNSIGNED;
} else if (encString.equals("alaw")) {
encoding = AudioFormat.Encoding.ALAW;
return new AudioFormat(encoding, rate, sampleSize,
channels, (sampleSize/8)*channels, rate, bigEndian);
public void run() {
duration = 0;
audioInputStream = null;
// define the required attributes for our line,
// and make sure a compatible line is supported.
AudioFormat format = getFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class,
format);
if (!AudioSystem.isLineSupported(info)) {
shutDown("Line matching " + info + " not supported.");
return;
// get and open the target data line for capture.
try {
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());
} catch (LineUnavailableException ex) {
shutDown("Unable to open the line: " + ex);
return;
} catch (SecurityException ex) {
shutDown(ex.toString());
return;
} catch (Exception ex) {
shutDown(ex.toString());
return;
// play back the captured audio data
int frameSizeInBytes = format.getFrameSize();
int bufferLengthInFrames = line.getBufferSize() / 8;
int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
byte[] data = new byte[bufferLengthInBytes];
int numBytesRead;
line.start();
try
while (thread != null) {
if((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
break;
if(data.length>0)
out.write(data, 0, numBytesRead);
out.flush();
catch (Exception e)
e.printStackTrace();
// we reached the end of the stream. stop and close the line.
line.stop();
line.close();
line = null;
// stop and close the output stream
try {
out.flush();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
} // End class CaptureAfter a few days work, I have completed the mian voice chat program. I know there are so many people like me that wants that. I post these program. i will complete gui work later. and there is a problem in the program. if the speaking one do not speak for a while, the listening client will hear noise. Can some one help me.
package com.longshine.voice;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
// The ServerSocket we'll use for accepting new connections
private ServerSocket ss;
// A mapping from sockets to DataOutputStreams. This will
// help us avoid having to create a DataOutputStream each time
// we want to write to a stream.
private Hashtable outputStreams = new Hashtable();
final int bufSize = 16384;
//current speak_man
private int speakman=-1;
// Constructor and while-accept loop all in one.
public Server( int port ) throws IOException {
// All we have to do is listen
listen( port );
private void listen( int port ) throws IOException {
// Create the ServerSocket
ss = new ServerSocket( port );
// Tell the world we're ready to go
System.out.println( "Listening on "+ss );
// Keep accepting connections forever
while (true) {
// Grab the next incoming connection
Socket s = ss.accept();
// Tell the world we've got it
System.out.println( "Connection from "+s );
// Create a DataOutputStream for writing data to the
// other side
DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
// Save this stream so we don't need to make it again
outputStreams.put( s, dout );
// Create a new thread for this connection, and then forget
// about it
new VoiceServer( this, s );
// Get an enumeration of all the OutputStreams, one for each client
// connected to us
Enumeration getOutputStreams() {
return outputStreams.elements();
// Send a message to all clients (utility routine)
void sendToAll( byte[] voice ,Socket socket) {
// We synchronize on this because another thread might be
// calling removeConnection() and this would screw us up
// as we tried to walk through the list
synchronized( outputStreams ) {
// For each client ...
for (Enumeration e = outputStreams.keys(); e.hasMoreElements(); ) {
// ... get the output stream ...
Socket tmp=(Socket)e.nextElement();
if(!tmp.equals(socket))
try {
DataOutputStream dout = new DataOutputStream(tmp.getOutputStream());
// ... and send the message
dout.write(voice,0,44096);
dout.flush();
} catch( IOException ie ) { System.out.println( ie ); }
// Remove a socket, and it's corresponding output stream, from our
// list. This is usually called by a connection thread that has
// discovered that the connectin to the client is dead.
void removeConnection( Socket s ) {
// Synchronize so we don't mess up sendToAll() while it walks
// down the list of all output streamsa
synchronized( outputStreams ) {
// Tell the world
System.out.println( "Removing connection to "+s );
// Remove it from our hashtable/list
outputStreams.remove( s );
// Make sure it's closed
try {
s.close();
} catch( IOException ie ) {
System.out.println( "Error closing "+s );
ie.printStackTrace();
// Main routine
// Usage: java Server <port>
static public void main( String args[] ) throws Exception {
// Get the port # from the command line
int port = Integer.parseInt( args[0] );
// Create a Server object, which will automatically begin
// accepting connections.
new Server( port );
package com.longshine.voice;
import java.net.*;
import java.io.*;
import java.sql.*;
import java.io.*;
import java.net.*;
public class VoiceServer extends Thread
// The Server that spawned us
private Server server;
final int bufSize = 16384;
// The Socket connected to our client
private Socket socket;
// Constructor.
public VoiceServer( Server server, Socket socket ) {
// Save the parameters
this.server = server;
this.socket = socket;
// Start up the thread
start();
// This runs in a separate thread when start() is called in the
// constructor.
public void run() {
try {
// Create a DataInputStream for communication; the client
// is using a DataOutputStream to write to us
DataInputStream din = new DataInputStream( socket.getInputStream() );
byte[] voice=new byte[44096];
// Over and over, forever ...
while (true) {
// ... read the next message ...
// int bytes = din.read(voice,0,44096);
int bytes = din.read(voice);
// ... and have the server send it to all clients
server.sendToAll(voice,socket);
} catch( EOFException ie ) {
// This doesn't need an error message
} catch( IOException ie ) {
// This does; tell the world!
ie.printStackTrace();
} finally {
// The connection is closed for one reason or another,
// so have the server dealing with it
server.removeConnection( socket );
package com.longshine.voice;
import java.io.*;
import java.net.*;
public class Client {
private String host="";
private String port="";
private Socket socket;
private DataOutputStream dout;
private DataInputStream din;
private Capture capture=null;
private Play play=null;
public Client(String host,String port) {
this.host=host;
this.port=port;
public void init()
try
socket = new Socket( host, Integer.parseInt(port));
din = new DataInputStream( socket.getInputStream() );
dout = new DataOutputStream( socket.getOutputStream());
capture=new Capture(dout);
play=new Play(din);
catch(Exception e)
e.printStackTrace();
public static void main(String[] args) {
Client client = new Client("172.18.220.176","5678");
client.init();
if(args[0].equalsIgnoreCase("say"))
client.capture.start();
if(args[0].equalsIgnoreCase("hear"))
client.play.start();
package com.longshine.voice;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
import javax.sound.sampled.*;
import java.text.*;
import java.net.*;
public class Play implements Runnable {
SourceDataLine line;
Thread thread;
String errStr=null;
DataInputStream in=null;
AudioInputStream audioInputStream;
final int bufSize = 16384;
int duration=0;
public Play(DataInputStream in)
this.in=in;
public void start() {
errStr = null;
thread = new Thread(this);
thread.setName("Playback");
thread.start();
public void stop() {
thread = null;
private void shutDown(String message) {
if ((errStr = message) != null) {
System.err.println(errStr);
if (thread != null) {
thread = null;
public void createAudioInputStream() {
if (in != null ) {
try {
errStr = null;
java.io.BufferedInputStream oin = new java.io.BufferedInputStream(in);
audioInputStream = AudioSystem.getAudioInputStream(oin);
} catch (Exception ex) {
ex.printStackTrace();
} else {
public void run() {
// reload the file if loaded by file
if (in != null) {
// createAudioInputStream();
// make sure we have something to play
// if (audioInputStream == null) {
// shutDown("No loaded audio to play back");
// return;
// reset to the beginnning of the stream
// try {
// audioInputStream.reset();
// } catch (Exception e) {
// shutDown("Unable to reset the stream\n" + e);
// return;
// get an AudioInputStream of the desired format for playback
AudioFormat format = getFormat();
audioInputStream=new AudioInputStream(in, format, AudioSystem.NOT_SPECIFIED);
AudioInputStream playbackInputStream = AudioSystem.getAudioInputStream(format, audioInputStream);
if (playbackInputStream == null) {
shutDown("Unable to convert stream of format " + audioInputStream + " to format " + format);
return;
// define the required attributes for our line,
// and make sure a compatible line is supported.
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
format);
if (!AudioSystem.isLineSupported(info)) {
shutDown("Line matching " + info + " not supported.");
return;
// get and open the source data line for playback.
try {
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format, bufSize);
} catch (LineUnavailableException ex) {
shutDown("Unable to open the line: " + ex);
return;
// play back the captured audio data
int frameSizeInBytes = format.getFrameSize();
int bufferLengthInFrames = line.getBufferSize() / 8;
int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
byte[] data = new byte[bufferLengthInBytes];
int numBytesRead = 0;
// start the source data line
line.start();
while (thread != null) {
try {
if ((numBytesRead = playbackInputStream.read(data)) == -1) {
break;
int numBytesRemaining = numBytesRead;
while (numBytesRemaining > 0 ) {
numBytesRemaining -= line.write(data, 0, numBytesRemaining);
} catch (Exception e) {
shutDown("Error during playback: " + e);
break;
// we reached the end of the stream. let the data play out, then
// stop and close the line.
if (thread != null) {
line.drain();
line.stop();
line.close();
line = null;
shutDown(null);
public AudioFormat getFormat() {
AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
String encString = "linear";
float rate = Float.valueOf("44100").floatValue();
int sampleSize = 16;
String signedString = "signed";
boolean bigEndian = true;
int channels = 2;
if (encString.equals("linear")) {
if (signedString.equals("signed")) {
encoding = AudioFormat.Encoding.PCM_SIGNED;
} else {
encoding = AudioFormat.Encoding.PCM_UNSIGNED;
} else if (encString.equals("alaw")) {
encoding = AudioFormat.Encoding.ALAW;
return new AudioFormat(encoding, rate, sampleSize,
channels, (sampleSize/8)*channels, rate, bigEndian);
} // End class Playback
package com.longshine.voice;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
import javax.sound.sampled.*;
import java.text.*;
import java.net.*;
public class Capture implements Runnable {
TargetDataLine line;
Thread thread;
String errStr=null;
DataOutputStream out=null;
AudioInputStream audioInputStream;
final int bufSize = 16384;
int duration=0;
public Capture(DataOutputStream out)
this.out=out;
public void start() {
errStr = null;
thread = new Thread(this);
thread.setName("Playback");
thread.start();
public void stop() {
thread = null;
private void shutDown(String message) {
if ((errStr = message) != null) {
System.out.println(errStr);
if (thread != null) {
thread = null;
public AudioFormat getFormat() {
AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;
String encString = "linear";
float rate = Float.valueOf("44100").floatValue();
int sampleSize = 16;
String signedString = "signed";
boolean bigEndian = true;
int channels = 2;
if (encString.equals("linear")) {
if (signedString.equals("signed")) {
encoding = AudioFormat.Encoding.PCM_SIGNED;
} else {
encoding = AudioFormat.Encoding.PCM_UNSIGNED;
} else if (encString.equals("alaw")) {
encoding = AudioFormat.Encoding.ALAW;
return new AudioFormat(encoding, rate, sampleSize,
channels, (sampleSize/8)*channels, rate, bigEndian);
public void run() {
duration = 0;
audioInputStream = null;
// define the required attributes for our line,
// and make sure a compatible line is supported.
AudioFormat format = getFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class,
format);
if (!AudioSystem.isLineSupported(info)) {
shutDown("Line matching " + info + " not supported.");
return;
// get and open the target data line for capture.
try {
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());
} catch (LineUnavailableException ex) {
shutDown("Unable to open the line: " + ex);
return;
} catch (SecurityException ex) {
shutDown(ex.toString());
return;
} catch (Exception ex) {
shutDown(ex.toString());
return;
// play back the captured audio data
int frameSizeInBytes = format.getFrameSize();
int bufferLengthInFrames = line.getBufferSize() / 8;
int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
byte[] data = new byte[bufferLengthInBytes];
int numBytesRead;
line.start();
try
while (thread != null) {
if((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
break;
if(data.length>0)
out.write(data, 0, numBytesRead);
out.flush();
catch (Exception e)
e.printStackTrace();
// we reached the end of the stream. stop and close the line.
line.stop();
line.close();
line = null;
// stop and close the output stream
try {
out.flush();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
} // End class Capture -
What is the best Videoing Chatting program to use for my Macbook Pro?
I have had Skype for a while now and recently I updated to Skype 5, and the call qaulity is absolutely miserable, it keeps being blurry and freezing and it's a pain to try and talk through. So I was wondering is there any changes or fixes I can do to possibly make it better or improve the quality of my calls? If not is there any other good video chatting programs with good call qualities for Mac?
Im using Skype on my macbook pro, just saying.How can you check if your wifi is good enough for a quality video call?
Yes I would post on Skypes forum, but there people their are not very helpful or supportive, so Im trying to get other people's opnions on ways to improve the call quality or find a better program.
Does anyone use any other video calling program that is just as good if not better? If so could you please mention it. I've looked on Google and I know some of the softwares or programs out there, but Id like to get peoples first hand experience with the programs and what they think of some of them out there. -
Is it possible to make an "internet" chat program?
I have already made a chat program for a LAN, but I want to somehow make it usable over the internet. Is there a way to make the program use your internet ip, instead of your lan ip?
Hello: I gott a similar trouble over writing an internet chat app. I have an app that works on a local server, works with a local database, i want it to work on internet, but i dont know how to do it, i also use a server app for replying client queries. I'm using sockets and i don't know how a client can works throught a LAN - proxy or router internet acces - to the app if i have to place it on a web server
-
Help me in my chat program please
hi,
Im doing chat program same as yahoo messenger using Java.Please help me in creating rooms....so that it will be a great help for me to finish my project..
Thanks in advance
PadmaPriya.hi,
Actually i have a common room in which people enter through a login screen and chat...it shows the user list .
what i want to do is i want to add a combo box in the login screen with mulitple rooms...the user should select rooms and then must be able to chat....in their rooms...
so that many rooms would function at a time..and people will be chatting correspondingly....can u please help me in doing that...
Thanks in advance
PadmaPriya. -
Disconnected from ANY chat program when I go into sleep mode
I am using an airport express connection with road runner. When my computer goes into sleep mode, any chat program I am using is disconnected -- this happens with AIM, iChat, and Netscape Navigator's chat screen. As soon as I move my mouse, or touch the keyboard, and go active, AIM automatically reconnects. Any ideas on how I can remain signed into a chat service when I go into sleep mode?
In sleep mode your mac only keeps the data in the RAM. all other things will be turned off, so that it´s impossible to stay online with the chat applications.
-
Creating Emoticons in a chat program
Hi all, I wish to write a chat program which has got emoticons?What is the best way to implement emoticons in a chat program? Thank you in advance...:)...
A subtle hint for the future topics: do not use the browser back button to edit the message. Rather use the edit button which you can find at the top right of your posted message (this edit button is available as long no one has replied on your message).
-
Chat program in release 4.7c
hi guys,
I was wondering how one can create a chat program in abap. As its possible in Java & .Net why an abaper under estimate himself. Now here imagine a simple chat program where one can send some text from his SAP GUI which will appear on others SAP GUI and viceversa. Dont think about some messangers like yahoo or gtalk.(dont over estimate being an abaper)
So i developed two programs one to send text & other to receive text. Send prg. is module pool and receive prg. is a simple report which has timer class which gets data from table every second so user dont have to press any button to receive the message.
To start chat you have to run both programs in your GUI where from send program you enter your name in one text field and your message in other text field by pressing enter it gets update in table field(not every time it insert new record, it simply update previous so table size would not increase). As the person with whoem you are chatting is also running both programs, your message appears in 2nd program on his GUI & yours also. followed by your name.
Both chat programs works fine with more then two users also. i tried to combine both program in one screen so user can send & receive chat from one screen. but due to timer class used, its not possible as receive program keeps refreshing for every 1 second.
so i am wondering is thier any way to run one modulepool program & one report in a single screen. some thing like screen splitting or docking???
you are welcome to share your ideas regarding chat in ABAP/4(release 4.7)
Regards,
SUDHIR MANJAREKARYes, thats right. There are few ABAP codes which you can find in the net and can improvise on that.
The program displays list of all users who are currently active on a list.
You can select user and select press button on the application tool bar to send a message.
Concerns here are: 1. The receiver cannot reply from the same popup. He has to run the program, select the user who has send message and reply. 2. You will not be able to see the entire message log.
For logging messages you can try creating standard text for tracking dialog between any two user and something of that sort.
regards,
S. Chandramouli. -
I'm trying to make a chatting program for my home network, but I can't find one good tutorial on using java and networking. They all just show me how to make a server and client programs on my own machine. Big bunch a help that'll give me. Can someone help me?
I've searched everywhere.
Thanks!Ah hell guys, if one of you is going to stand still and let the other run over, first, let me film it. Faces of Death needs a new movie! Second, let's use something better than a car for crying out loud! I'm thinking of a crane and ball, swing that sucker as fast as possible, or let's see if like in the cartoons, dropping a piano really does allow you to break through it, or if it would just flatten you. At least use a friggin' 18 wheeler or something so we can see body parts fly all over the place!
-
Hi everyone,
I'm writing a simple chat program as a assignment at my Uni. I get stucked with the client GUI. I want to create a GUI like that of Yahoo messenger which has a list of connected users displayed on the GUI. When u double click on the name of the user, u will get connected to that user. I have no idea about creating a GUI list like this one. Can anybody help me with this? Thanks in advance!There are many tutorials on this site; check the "tutorials" link on the column on the left.
Here are ones about GUIs:
http://developer.java.sun.com/developer/onlineTraining/GUI/
I'd suggest skipping over any tutorials prior to JDK 1.1 or even 1.2.
Read more recent ones. There have been significant improvements, especially w.r.t. event handling, between 1.0 and 1.1. -
How to use afcs, i want to make video chat program using afcs....
hello, i want to make video chat program in android air.
so i try to afcs(Adobe LiveCycle Collaboration Service), but it shut down that create new account..
how to create new account??
how to download afcs SDK??
help.. me .. please..~~~Hi Cbigb,
You can download the current LCCS SDK here..
https://cocomo.acrobat.com/download/payload.zip
If you are interested in talking to us here at Influxis about our new service offering please contact Wesley Daggett at 661-775-3936 or via e-mail [email protected]
cheers,
James -
Integrate A Chat Program with a Web Page
iIn JSP Based Web Page
Integrate A Chat Program with a Web PageI have an iPad 3rd generation and I get that message as well so it has nothing to do with having an iPad 2. The message means exact,y what it says, there was a problem loading the web site. In some situations, it just might be a problem with the website itself. Please note that I said in "some" situations. If you are getting this message every single time that you try to load a page, something is wrong.
Did you clear Safari, close all apps and then reset the iPad? Settings>Safari>Clear history and website data.
Now close all apps. In order to close apps, you have to drag the app up from the multitasking display. Double tap the home button and you will see apps lined up going left to right across the screen. Swipe to get to the app that you want to close and then swipe "up" on the app preview thumbnail to close it.
Next, reset the iPad by holding down on the sleep and home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider if it appears on the screen - let go of the buttons. Let the iPad start up. -
Is that possible ? (Chat Program)
I just found a great source code for a basic Server/Chat Program, but both works on a Frame... I want the Client to run on an Applet (Web Page) and the server to run on a PC in a Frame.
Is that possible... ? If yes, how do I do that? I can send the source code if you want.Hi,
I am developing a socket server and client application for some other purpose than chatting. In my application, the <b>Log Server</b> is a Daemon Thread always be listening to the client requests. On listening to a request it spawns a <B>RequestProcessor</B> thread to process the requests.
The client is a session manager servlet. When the new HTTP request is taken by it, it has to write the status of the HTTP request into to the remote log files on the Log server. So at the beginning HTTP request, it has to write into the remote log file. And then process the request which may take a few seconds. At the HTTP request process, this has to write again into the remote log file on Log Server.
In my code now: The session manager will open a client socket to the server. At the beginning of the HTTP request, it will getOutputStream() of that socket and flushes the data to the OutputStream. Please note that it doent close that client socket. Then it does some processing. Then at the beginning of the HTTP request, it will re-use the same client socket and get the outputStream of that socket and flushes the data to the OutputStream.
If I do this, what I observed is unless i close the client socket, the data is not actually being written to the outputstream. The server side <B>RequestProcessor</B> thread is able to read the data from the sockets inputstream, only when the client socket is closed.
Please suggest me how to resolve this. So that when ever the data is flushed to the outputsteram, the server side <B>RequestProcessor</B> thread must be able to read that immediately.
Please let me know asap.
Thanks in advance
Murali -
Building a chat program in java
i am trying to build a chat program in java but don't know how to start or where to get the source code. Chatting can be done with the user of the selected IP address displayed in the console.
Can anyone help me ?hey, i'm reading this book now, try this link:
http://manning.spindoczine.com/sbe/
i think it has something about chat program. good luck:)
Maybe you are looking for
-
Photoshop CC 2014 does not show up in Default Programs to associate with correct extensions.
I am trying to re-associate file types such as .jpg with Photoshop CC 2014. The executable file does not show up even after I select it by browsing to it. What do I need to do so my image file types open in Photoshop like they did in CC / CS6? I h
-
Multi-Master Replication over the WAN
DS verison: 5.1 sp1 Did any one implement multi-master replication across the WAN or different IP subnets?
-
My ipod classic will not charge or turn on
MY IPOD CLASSIC WILL NOT CHARGE OR TURN ON
-
Problems connecting to internet through airport extreme
Hi everyone I am tyring to connect to the internet. I have Charter Digital at the highest speed. When I connect directly through the cable modem using DHCP i can connect to the internet just fine, but when I use the Airport using assing multiple IP a
-
How to make a Loadvars sendAndLoad request from embedded swf in flex
I've developed a simple flex app with embedded swf. Basically swf use Loadvars to get data from particular database table. Ok, when I tested the flex app on localhost it is works fine and embedded swf make its sendAndLoad calls correctly. But! When i