Java chat programs

hi..am looking for sample java programs where a server can communicate to multiple clients and viseversa....could anyone by any chance have done similar programs or knows a link to such programs?
thanks
ps:i already checked in the forum and found a number of incomplete codes..so i'm looking for something complete.

It doesn't follow any naming convention as i wrote it a long time back when ( I didn't know what coding conventions were then). However it will give you a basic idea
The server code
     import java.io.*;
     import java.net.*;
     class kserverreceive implements Runnable
          Socket client1;
          BufferedReader in;
          String fromuser;
          Thread t;
          kserverreceive(Socket client1,BufferedReader in)
               this.client1=client1;
               this.in=in;
               t=new Thread(this);
               t.start();
          public void run()
               try
                    while((fromuser=in.readLine())!=null)
                         System.out.println(fromuser);
               catch(IOException e)
                    System.out.println("IOException encountered");
          //System.out.println("client has disconnected");
     class kserversend implements Runnable
          Socket client2;
          BufferedReader stdIN=new BufferedReader(new InputStreamReader(System.in));
          PrintWriter out;
          String touser;
          Thread t;
          kserversend(Socket client2,PrintWriter out)
               this.client2=client2;
               this.out=out;
               t=new Thread(this);
               t.start();
          public void run()
               try
                    while((touser=stdIN.readLine())!=null)
                         out.println(touser);
               catch(IOException e)
                    System.out.println("IOException encountered");
          //System.out.println("the client has disconneceted");
     public class kserver
          public static void main(String args[]) throws IOException
               ServerSocket server=null;
               Socket client=null;
               BufferedReader in;
               PrintWriter out;
               kserverreceive client1;
               kserversend client2;
               try
                    server=new ServerSocket(7777);
               catch(IOException e)
                    System.out.println("couldnt listen on port 7777");
                    System.exit(1);
               try
                    while(true)
                         client=server.accept();
                         in=new BufferedReader(new InputStreamReader(client.getInputStream()));
                         out=new PrintWriter(client.getOutputStream(),true);
                         System.out.println("connection established");
                         client2=new kserversend(client,out);
                         client1=new kserverreceive(client,in);                    
               catch(Exception e)
                    System.out.println("accept failed:"+e);
                    System.exit(1);
               //This is if you want to accept only a single client request
               /*String outline;
               BufferedReader inread=new BufferedReader(new InputStreamReader(client.getInputStream()));
               while((outline=inread.readLine())!=null)
                    System.out.println(outline);
//               inread.close();
               client.close();
               server.close();
          The client code
     import java.io.*;
     import java.net.*;
     class kclientsend implements Runnable
          Socket client1;
          PrintWriter out;
          Thread t;
          String touser;
          BufferedReader stdIN=new BufferedReader(new InputStreamReader(System.in));
          kclientsend(Socket client1,PrintWriter out)
               this.client1=client1;
               this.out=out;
               t=new Thread(this);
               t.start();
          public void run()
               try
                    while((touser=stdIN.readLine())!=null)
                         out.println(touser);
               catch(IOException e)
                    System.out.println("IOException encountered");
          //System.out.println("The client has disconnected");
     class kclientreceive implements Runnable
          Socket client2;
          BufferedReader in;
          String fromuser;
          Thread t;          
          kclientreceive(Socket client2,BufferedReader in)
               this.in=in;
               this.client2=client2;               
               t=new Thread(this);
               t.start();
          public void run()
               try
                    while((fromuser=in.readLine())!=null)
                         System.out.println("["+client2.getInetAddress().toString()+"]::"+client2.getInetAddress().getHostName()+"::"+fromuser);
               catch(IOException e)
                    System.out.println("IOException encountered");
          //System.out.println("The client has disconnected");
     public class kclient
          public static void main(String args[]) throws Exception
               Socket client=null;
               PrintWriter out=null;
               BufferedReader in=null;
               kclientsend client1;
               kclientreceive client2=null;
               try
                    client=new Socket("NAMI",7777);
                    out=new PrintWriter(client.getOutputStream(),true);
                    in=new BufferedReader(new InputStreamReader(client.getInputStream()));
                    System.out.println("connection established successfully");
                    client1=new kclientsend(client,out);
                    client2=new kclientreceive(client,in);
               catch(UnknownHostException e)
                    System.out.println("NAMI not found"+e);
                    System.exit(1);
               catch(IOException e)
                    System.out.println("couldnt get IO for NAMI"+e);
                    System.exit(1);
               /*String fromuser;
               BufferedReader stdIN=new BufferedReader(new InputStreamReader(System.in));
               while((fromuser=stdIN.readLine())!=null)
                    out.println(fromuser);
               Thread.sleep(100000);
               out.close();
               // stdIN.close();
               client.close();
               Message was edited by:
qUesT_foR_knOwLeDge

Similar Messages

  • Java chat program, works on single PC, but not over internet?

    I got bored so I started writing a chat client in java, its IRC style, a server and as many clients as you want. It works fine on a single computer (using 127.0.0.1 as the IP) but not over the internet.
    I've tried running the server and client on my home PC, set up the ports to be forwarded on my router and enabled them in the windows firewall but I get the error "Connection refused" when trying to connect using my external IP (ISP) address, same with me running the server and a mate running the client.
    The class chatHandler was basically stolen off the internet, the rest I wrote myself or modified bits of code to suit. I wrote it in netbeans with the GUI builder.
    I've hosted both projects in the single zip, if you want to run the application just open the .jar file in the dist folders, or view the source via the src folder, or alternatively you can load the project up in NetBeans so its easier to play with the GUI.
    So yeah if anyone can help me out with why its not working that'd be great, I've added the port to my firewall (default 60111). My ultimate goal is to implement an actual protocol so it isn't just sending plain text, then I can easily send files to mates etc.
    http://rapidshare.com/files/208309140/ChatProgram.zip.html
    Edited by: rolls on Mar 12, 2009 4:58 AM

    what I have done recently is this:
    have added java.exe, javaw.exe, the ports Im using to the windows firewall and also the ports I am using to my router.
    I have also tried changing :
    server = new ServerSocket(port);
    to:
    InetAddress IP = InetAddress.getByName(IPAddress);
    server = new ServerSocket(port, backlog, IP);
    (IPAddress = 192.168.1.3 my lan NIC)
    As I believe it was binding to my local loopback adaptor, hence not seeing any packets when using a packet analyser, however now I get an exception, after printing a stacktrace from the client I get this.
    However I can now connect using 192.168.1.3 just not using my external IP address.
    java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl .java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSoc ketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.j ava:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.j ava:366)
    at java.net.Socket.connect(Socket.java:519)
    at java.net.Socket.connect(Socket.java:469)
    at java.net.Socket.<init>(Socket.java:366)
    at java.net.Socket.<init>(Socket.java:180)
    at chatclient.Client.run(Client.java:60)
    at java.lang.Thread.run(Thread.java:619)
    Why is my connection getting refused? I've set up a virtual server and port forwarding on my router, and turned off the windows firewall.

  • 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:)

  • Voice chat program

    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 Capture

    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 Capture

  • 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.

  • Newbie question concerning java chat

    Hi everyone,
    I'm going to program at chat-service in java at school. Since I'm still rather new at this game, I was wondering if anyone knew any good tutorials to start with. I'm also very interested in recommendations as to which java techniques would be best.
    My initial thoughts on the project are:
    1) it's going to be controlled by a central server (using servlets and JSP).
    2) I wish to overcome problems concerning firewalls etc.
    3) I took a peek in the book "Java Servlet Programming". It said that there were 3 possible implementations: HTTP, Sockets and RMI. I wonder if there are any other possibilities? JMS for instance?
    4) I wish to implement the service in such a way, that different users can approach the service differently (eg. user A with HTTP, and user B with RMI). this should be completely transparent. But is that possible?
    Well, thats basically all. I hope someone have some tips or experiences to share. I doubt that I'm the first (or the last) one embarking on a project like this.

    I've found some links in previous posts.
    http://www.javaworld.com/javaworld/jw-01-1997/jw-01-chat_p.html
    And the section on "Java Shared Data Toolkit"

  • 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 MANJAREKAR

    Yes, 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.

  • Network chat program

    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!

  • GUI for chat program

    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.

  • Hi, I love Java Chat.

    Hi, I'm interested in learning more about java chat. How it works and how to do all the special functions. It seems really popular and I feel like a novice because I only know how to type and log in.
    Oh, pardon me, I'm Eanus. I like fishing, history and such.
    Nice you meet you.

    Hi,
    I'm nice to meet you.
    Sorry to say but this is a programming forum, and not a forum where you can ask about how you use a certain program.
    Good luck
    Kaj

  • 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

  • Java chat console not appearing

    hi there. please help. i am trying to use java chat console but cannot get it to work. i have tried everthing that the chat site tech asks of me, but still no luck. anyone else had this problem PLEASE let me know how u solved it.
    many thanks

    This isn't really a Java programming question... it's more a "something's disconfigured on someone's computer" question... but, just for fun, here are the things you need to check:
    Does your browser have a Java plug-in installed? Is the version of the Java plug-in compatible with the Java chat version the server is using? Do you have Java enabled in your browser? Do you have this problem with other Java applets from other sites, or only this one?
    I'd recommend upgrading your JVM (or downgrading it, if the site is really that broken), checking your browser settings, and possibly testing with another browser.
    Sincerely,
    Dylan

  • Online chat program

    hey guys, im new to the whole networking thing, and this is my first attempt at using the internet. i am making a chat program, and having some troubles.
    import java.net.*;
    import javax.swing.*;
    import java.io.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class CHAT2 extends JFrame implements Runnable, ActionListener
        Thread Client = new Thread(this, "Client");
        DatagramSocket ds;
        public int buffer_size = 1024;
        public byte buffer[] = new byte[buffer_size];
        public final int PORT = 3677;
        JTextField jt;
        JTextArea jto;
        public CHAT2() {
        Thread.currentThread().setName("Server");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        try {
            ds = new DatagramSocket(PORT);
            }catch(SocketException ec) {
        JPanel jp = new JPanel();
        jp.setLayout(new GridLayout(2,2));
        setTitle("MChat");
        setSize(400,400);
        setResizable(false);
        jt = new JTextField();
        jto = new JTextArea();
        jto.setFont(new Font("Arial", Font.BOLD, 12));
        jto.setForeground(Color.BLUE);
        jto.setEditable(false);
        //jt.setSize(100,20);
        //jt.setLocation(10,50);
        JButton b = new JButton("Send Message");
        //b.setSize(100,40);
        //b.setLocation(10,100);
        getContentPane().setLayout(new BorderLayout());
        //getContentPane().add(b);
        jp.add(jt);
        jp.add(b);
        getContentPane().add(jto, BorderLayout.CENTER);
        getContentPane().add(jp, BorderLayout.SOUTH);
        b.addActionListener(this);
        Client.start();
    public void run() {
        try {
            for(;;) {
                buffer = new byte[buffer_size];
                DatagramPacket p = new DatagramPacket(buffer, buffer.length);
            try {
                ds.receive(p);
        }catch(IOException ec) {
        String temp = new String(p.getData(), 0, p.getLength());
        System.out.println(temp);
        if(jto.getText().length() > 1) jto.setText(jto.getText() + "\n" + temp);
        else jto.setText(temp);
        Thread.sleep(1);
        }catch(InterruptedException ec) {
    public void actionPerformed(ActionEvent ae)
        send(jt.getText());
    public void send(String e)
        int c = 0;
        while(c < e.length()) {
        buffer[c] = (byte) (e.charAt(c) );
        c++;
        try {
        ds.send(new DatagramPacket(buffer,c, InetAddress.getLocalHost(), PORT));
        }catch(IOException ec) {
    public static void main(String args[])
        System.out.println(new Date().getDay());
        CHAT2 ch = new CHAT2();
        ch.setVisible(true);
    }it works when i use it on my computer, but when trying to go across my network it does not. i have a feeling it traces back to this line
    ds.send(new DatagramPacket(buffer,c, InetAddress.getLocalHost(), PORT));
    any ideas on how to fix it?
    (remember i am very new to networking, so dont expect me to know much....)

    InetAddress.getLocalHost() gets your localhost ip. i.e. the ip of the computer you are running the program on which means you will send the package to the same computer. to send it to another computer enter the ip-address of it.

  • Need Help with Simple Chat Program

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.

  • Adding nicknames to chat program

    Hi there,
    I'm developing a chat program in java for school.
    I already have the basics. I have a client, a server, and so on...
    The communication had already been set right.
    But now I want to let the client (user, who wants to chat) choose their nickname.
    There cannot be 2 persons with the same nickname.
    So I probably have to save those nicknames at the server.
    How is the best way to approach this?
    Just sending a nickname as a string is probably not a good way. Because the server had to make a difference between text (that has to be sent to every client) and other data (like a nickname).
    I have no idea how to do this. How is this handled by other chat programs?
    I hope someone can point me some ways to solve this.
    Thanks in advance!

    I see that you have every string that comes in as a message from that client.
    What you should do is have the client type in his name before.
    The string contains a special code to tell the server that it is a name. Such as: "&#60;incomingnickname>ejito&#60;/incomingnickname>". When the server gets this information it will parse the nickname and send that name to respective database of current clients connected. It will then allow that person to speak and show up in the room.
    The server checks whether names are already in use by looking through the database of clients.
    If that name is currently taken, then the sever will send back a "&#60;nicknamefailed> That nick is taken! Choose another&#60;/nicknamefailed>", and not allow the user to talk in the room until he gets a new name. The server will just trash all incoming messages from that client.
    This is pretty secure. Since the server does the checking, and also prevents the user from speaking or appearing in the chat, it will prevent people from trying to duplicate the person's name.

Maybe you are looking for

  • SSO with BSP Not Working

    Hi I am running Nw2004s Portal with ECC5 as BackEnd. I have Configured the ECC5 for SSO using RZ10 and strustsso2. The Portal UserIDs are same as those in  ECC5 . The SSO is working fine with ESS in the Portal. But when i run  a BSP iView then it ask

  • Best of the Month – October '14

    Time passes, months go by, technologies evolve and replace their old selves… but the Forum doesn’t grow old, at least not by its sprit. It still has the same rush of customers swarming through its boards, trying to get help for their HP products and

  • HT1420 why can I not download my iTunes to my Samsung galaxy tablet 10.1?

    I bought a streaming movie but cannot play this without iTunes.   I would have bought this from flixster if I had known it would only go to iTunes and I cannot stream this on my ultraviolet account. I won't buy another movie from iTunes again. I trie

  • URGENT PLZ- output

    Dear SAP Guru, I need to reprint some old invoices for salesorganisation ABCD order & delivery related. When I re-select them through transaction VF31 a lot of them go straight to the LOCL printer instead of the spooler & having waiting status. (I ma

  • IMac bootup issues and spinning beach ball of death.

    Hello Hello. So I was recently given a brand new iMac 27inch by Apple, due to the death of my 2008 24inch iMac. Everything has been going great with it until today. I restarted it at some point this afternoon, and ever since then it has been acting q