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.
Similar Messages
-
Help needed with a chat program
Hi everyone! i'm busy with a client/server chat program. I'm really stuck because i can't seem to get the messages from one client to show on the other client's screen.
If one client sends a message to another client, the server receives the message, but the second client does not receive the message.
Here is the server code that sends messages to the clients:
BufferedReader incomeReader = null;
PrintWriter outWriter = null;
try {
incomeReader = new BufferedReader(new InputStreamReader (incomingSocket.getInputStream()));
outWriter = new PrintWriter(incomingSocket.getOutputStream(),true);
}catch (Exception e) {
System.out.println("error handling a client: " + e);
System.exit(-1);
line = incomeReader.readLine();
textArea.append(line + "\n");
outWriter.println(line);
The server is suppose to put the message it receives on the text area on the server screen, and then send the message to all clients connected to it.
I hope somebody will be able to help me...The code posted just sends any data it receives back to the person who sent it. To get it to work there, you probably should flush after the println. I believe your mother taught you always to flush. It seems you have forgotten.
-
Somebody please help me. I can't seem to get my client/server program to work well. The problem is that when a client sends a message to another client, the other client doesn't receive that message. Instead, the server and the client that sent the message are the ones that receive the message.
Here is the server code that processes the messages:
BufferedReader incomeReader = null;
PrintWriter outWriter = null;
try {
incomeReader = new BufferedReader(new InputStreamReader(incomingSocket.getInputStream()));
outWriter = new PrintWriter(incomingSocket.getOutputStream(),true);
}catch (Exception e) {
System.out.println("error handling a client: " + e);
System.exit(-1);
line = incomeReader.readLine();
outWriter.println(line);
outWriter.flush();
Well, i hope somebody will be able to help....incomeReader = new BufferedReader(new InputStreamReader(incomingSocket.getInputStream()));
outWriter = new PrintWriter(incomingSocket.getOutputStream(),true);Quite what you programmed. "incomingSocket" sends the message and gets it back. -
Need urgent help with a new Z program please
I have to write a program that finds files matching some pattern, for example I have files test1,test2,test3 in a directory then if I pass test* as parameter it should find all the files i.e, test1,2,3. I have to then store the files in internal table, loop through it and have to call some other program zzz that has a selection screen with default parameters.
1) Is there any function that I can call that gives all the files by passing wild card (ex:test*) and store the files in internal table?
2) How do I call some other program ZZZ from my program?
3) How do I pass values from my program to other program's selection screen?
Your help would be greatly appreciated.
Thanks.
MithunHi,
1) data: FILE_TABLE TYPE STANDARD TABLE OF FILE_INFO.
data: wa_file type file_info.
data: count type i.
CALL METHOD CL_GUI_FRONTEND_SERVICES=>DIRECTORY_LIST_FILES
EXPORTING
DIRECTORY = 'C:\'
FILTER = 'test.*'
files_only = 'X'
changing
FILE_TABLE = file_table[]
count = count.
loop at file_table into wa_file.
write: / wa_file-filename.
endloop.
2) You can use SUBMIT statement to call another program..
3) In the SUBMIT statement you can use the WITH addition to pass the values to the program.
Thanks,
Naren -
Help:something whin a Chat program
source code below:
public class ChatServer extends UnicastRemoteObject implements ... {
ClientCallbacks cl = null;
public void connect(ClientCallbacks cl) throws RemoteException {
this.cl = cl;
public void sendMessage(String msg) throws RemoteException {
cl.receiveMessage(msg);
public class Client extends JFrame implements ClientCallbacks{
ChatServer remoteServer;
remoteServer.connect(this);
TextArea messages = new TextArea(10,50);
public void receiveMessage(String msg) throws java.rmi.RemoteException
// Complete callback implementation
messages.setText(msg);
// ((JFrame)callbacks).show();
public interface ClientCallbacks extends java.rmi.Remote
public void receiveMessage(String msg) throws java.rmi.RemoteException;
compiling is OK! running is OK!
the callbacks cl.receiveMessage really run, but it is running on the server side and not on the client side.
so, the TextArea messages on the client side can't be changed.
if the statement ((JFrame)callbacks).show() which is been comment above is active, a gui will be display
on the server side. I want not that.
the remoteServer object is been get from Naming.lookup(...).
and, the cl is been transfered by the method remoteServer.connect(cl);
I want the cl.receiveMessage(...) can change the TextArea messages on the client side. It maybe need that
method receiveMessage(...) performed on client side, which is not same as now.
maybe, in the program, the object cl is been serialized to the server and run on the server side, it isn't same as that of the remoteServer.
I want it performed like remoteServer, and can change the client. What should I do?Maybe, that is really a problem, didn't it?
-
My MacBook get's hot really quick and then discharge's quickly without opening any program, please help.
I have checked the cooling fan, and it's working, and I took it to an IT technician and he said my hardware is allright, so is it a problem from the OS it self??
OS X(10.8.5)Restart with the Option key held down and the Mac OS X install disk inserted, provide the firmware password, click on the DVD, press the button with the straight arrow, access the firmware settings, disable the password, and use FireWire Target Disk mode. If you can't do that or it doesn't work, contact Apple.
(38384) -
i have windows 8 and I got this error "Adobe Photoshop has stopped working" whenever I start a program. please help. how can I fix this problem? many thanks
Please read these and proceed accordingly:
http://blogs.adobe.com/crawlspace/2012/07/photoshop-basic-troubleshooting-steps-to-fix-mos t-issues.html
http://forums.adobe.com/docs/DOC-2325 -
I need help instantly on this program please
import java.util.*;
public class D3
private static int[] z = new int[100000];
private static int first=z[0];
private static int last=z[n-1];
private static int n=100000;
public static void main(String args[])
Scanner input=new Scanner(System.in);
for(int i=0;i<z.length;i++)
z=2*i;
int seqSearch(z;50000;n); //method call 4 key where key=mid
int binSearch(z;first;last;50000);
int seqSearch(z;35467;n); //method call 4 key where key in the left half
int binSearch(z;first;last;35467);
int seqSearch(z;89703;n); //method call 4 key where key in the right half
int binSearch(z;first;last;89703);
public int seqSearch(int z[];int key;int n)
long start = System.currentTimeMillis();
int count=0;
int ans=-1;
for(int i=0;i<n;i++)
if z[i]=key
count++
{ans=i
break;}
return ans;
long elapsed = System.currentTimeMillis() - start;
System.out.print("Execution Time:" + elapsed);
System.out.print("# of Basic Operations:" + count);
public int binSearch(int z[];int first;int last;int key)
long start = System.currentTimeMillis();
int count=0;
if(last<first){
count++;
index=-1;
else
count++;
int mid=(first+last)/2
if(ket=z[mid]{
index=mid;
else
if(key<z[mid]){
index = binSearch(z[];first;mid-1;key);
else
index=binSearch(z[];mid+1;last;key);
return index;
long elapsed = System.currentTimeMillis() - start;
System.out.print("Execution Time:" + elapsed);
System.out.print("# of Basic Operations:" + count);
// if anyone could tell me whats wrong with my code i'd be greatful...the program is supposed to perform binary and sequential search on a sorted array of 100000 numbers.once on an item in the middle of the array once on the right side of it and once on the left side...i also need to count the number of basic operations for the same number in both sequential and binary to see whats better.and i need to check the time...plz i need help now,,,"Guide to a first-time poster"
you need to add exclamation marks to signify how urgent it is
e.g.
i need help instantly on this program please!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
capital letters is better
I NEED HELP INSTANTLY ON THIS PROGRAM PLEASE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
starting the italics on line 1, better again
import java.util.*;
public class D3
private static int[] z = new int[100000];
private static int first=z[0];
private static int last=z[n-1];
private static int n=100000;
public static void main(String args[])
Scanner input=new Scanner(System.in);
for(int i=0;i<z.length;i++)
z=2*i;
int seqSearch(z;50000;n); //method call 4 key where key=mid
int binSearch(z;first;last;50000);
int seqSearch(z;35467;n); //method call 4 key where key in the left half
int binSearch(z;first;last;35467);
int seqSearch(z;89703;n); //method call 4 key where key in the right half
int binSearch(z;first;last;89703);
public int seqSearch(int z[];int key;int n)
long start = System.currentTimeMillis();
int count=0;
int ans=-1;
for(int i=0;i<n;i++)
if z=key
count++
{ans=i
break;}
return ans;
long elapsed = System.currentTimeMillis() - start;
System.out.print("Execution Time:" + elapsed);
System.out.print("# of Basic Operations:" + count);
public int binSearch(int z[];int first;int last;int key)
long start = System.currentTimeMillis();
int count=0;
if(last><first){
count++;
index=-1;
else
count++;
int mid=(first+last)/2
if(ket=z[mid]{
index=mid;
else
if(key><z[mid]){
index = binSearch(z[];first;mid-1;key);
else
index=binSearch(z[];mid+1;last;key);
return index;
long elapsed = System.currentTimeMillis() - start;
System.out.print("Execution Time:" + elapsed);
System.out.print("# of Basic Operations:" + count);
and what about the dukes, offer 10 (never to be awarded, of course)
do this, then sit back and watch the replies roll in. -
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.
-
When I'm on iChat, it doesn't show the video chat icon. When I try to change it, it tells me that my camera doesn't support video chats. Please help
A lot of folks fix these kinds of issues with a simple re-start of the phone.
Regards
TD -
Need some help with a program Please.
Well, im new here, im new to java, so i need your help, i have to make a connect four program, my brother "Kind of" helped me and did a program for me, but the problem is i cant use some of those commands in the program and i have to replace them with what ive learned, so i will post the program and i will need your help to modify it for me.
and for these programs, also i want help for:
They have errors and i cant fix'em
the commands that i've leaned:
If statements, for loops, while loops,do while, strings, math classes, swithc statement, else if,logical operators,methods, one and two dimensional arrays.
Thanx in advance,
truegunner
// Fhourstones 3.0 Board Logic
// Copyright 2000-2004 John Tromp
import java.io.*;
class Connect4 {
static long color[]; // black and white bitboard
static final int WIDTH = 7;
static final int HEIGHT = 6;
// bitmask corresponds to board as follows in 7x6 case:
// . . . . . . . TOP
// 5 12 19 26 33 40 47
// 4 11 18 25 32 39 46
// 3 10 17 24 31 38 45
// 2 9 16 23 30 37 44
// 1 8 15 22 29 36 43
// 0 7 14 21 28 35 42 BOTTOM
static final int H1 = HEIGHT+1;
static final int H2 = HEIGHT+2;
static final int SIZE = HEIGHT*WIDTH;
static final int SIZE1 = H1*WIDTH;
static final long ALL1 = (1L<<SIZE1)-1L; // assumes SIZE1 < 63
static final int COL1 = (1<<H1)-1;
static final long BOTTOM = ALL1 / COL1; // has bits i*H1 set
static final long TOP = BOTTOM << HEIGHT;
int moves[],nplies;
byte height[]; // holds bit index of lowest free square
public Connect4()
color = new long[2];
height = new byte[WIDTH];
moves = new int[SIZE];
reset();
void reset()
nplies = 0;
color[0] = color[1] = 0L;
for (int i=0; i<WIDTH; i++)
height[i] = (byte)(H1*i);
public long positioncode()
return 2*color[0] + color[1] + BOTTOM;
// color[0] + color[1] + BOTTOM forms bitmap of heights
// so that positioncode() is a complete board encoding
public String toString()
StringBuffer buf = new StringBuffer();
for (int i=0; i<nplies; i++)
buf.append(1+moves);
buf.append("\n");
for (int w=0; w<WIDTH; w++)
buf.append(" "+(w+1));
buf.append("\n");
for (int h=HEIGHT-1; h>=0; h--) {
for (int w=h; w<SIZE1; w+=H1) {
long mask = 1L<<w;
buf.append((color[0]&mask)!= 0 ? " @" :
(color[1]&mask)!= 0 ? " 0" : " .");
buf.append("\n");
if (haswon(color[0]))
buf.append("@ won\n");
if (haswon(color[1]))
buf.append("O won\n");
return buf.toString();
// return whether columns col has room
final boolean isplayable(int col)
return islegal(color[nplies&1] | (1L << height[col]));
// return whether newboard lacks overflowing column
final boolean islegal(long newboard)
return (newboard & TOP) == 0;
// return whether newboard is legal and includes a win
final boolean islegalhaswon(long newboard)
return islegal(newboard) && haswon(newboard);
// return whether newboard includes a win
final boolean haswon(long newboard)
long y = newboard & (newboard>>HEIGHT);
if ((y & (y >> 2*HEIGHT)) != 0) // check diagonal \
return true;
y = newboard & (newboard>>H1);
if ((y & (y >> 2*H1)) != 0) // check horizontal -
return true;
y = newboard & (newboard>>H2); // check diagonal /
if ((y & (y >> 2*H2)) != 0)
return true;
y = newboard & (newboard>>1); // check vertical |
return (y & (y >> 2)) != 0;
void backmove()
int n;
n = moves[--nplies];
color[nplies&1] ^= 1L<<--height[n];
void makemove(int n)
color[nplies&1] ^= 1L<<height[n]++;
moves[nplies++] = n;
public static void main(String argv[])
Connect4 c4;
String line;
int col=0, i, result;
long nodes, msecs;
c4 = new Connect4();
c4.reset();
BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
for (;;) {
System.out.println("position " + c4.positioncode() + " after moves " + c4 + "enter move(s):");
try {
line = dis.readLine();
} catch (IOException e) {
System.out.println(e);
System.exit(0);
return;
if (line == null)
break;
for (i=0; i < line.length(); i++) {
col = line.charAt(i) - '1';
if (col >= 0 && col < WIDTH && c4.isplayable(col))
c4.makemove(col);
By the way im using Ready to program for the programming.You can't really believe that his brother did this
for him...I did miss that copyright line at the beginning when
I first looked it over, but you know, if it had been
his brother, I'd be kinda impressed. This wasn't a
25 line program. It actually would have required
SOME thought. I doubt my brother woulda done that
for me (notwithstanding the fact that I wouldn't need
help for that program, and my brother isn't a
programmer).I originally missed the comments at the top but when I saw the complexity of what was written then I knew that it was too advanced for a beginner and I relooked through the code and saw the comments. -
Firewall burrowing/chat program help
I'm trying to develop a person-server-person chat program with java with the ability to burrow through firewalls. I'm using the example program from 1996 at: http://developer.java.sun.com/developer/technicalArticles/InnerWorkings/Burrowing/ as a guide.
I can get the applet up and running, but it won't connect to the server. The server says "Ready...", but neither connects to each other. They are both supposedly using port 6006.
When looking through the code of SimpleChatServer.java, I can't find where it designates an IP address, and can't figure out just how the applet is supposed to connect to the server.
Thanks everyone,
Mark(Most if this code is from the example in the URL I first gave)
Here's the important code (trying 8080 this time):
Server:
int port = 8080;
// Get the port number
if (argv.length == 1)
port = Integer.parseInt(argv[0]);
// Create a server socket on the given port
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port: " +
port + ", " + e);
System.exit(1);
// Allocate a vector for all open connections to clients.
Vector connections = new Vector();
System.out.println("port: "+port+"Serversocket: "+ss);
System.out.println("Ready...");
Output from DOS prompt is:
port: 8080Serversocket: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=8080]
Ready...
From the Client/Applet side, run from IE 5:
String str = getParameter("port");
int port = (str != null) ? Integer.parseInt(str) : 8080;
connection = new ServerConnection(getCodeBase().getHost(),port);
System.out.println("connection: "+connection);
Output from java console:
connection: ServerConnection@de9ac4
Error getting a new connection to read from
I have no idea what ServerConnection@de9ac4 means (I know where it came from, just not what it means).
Thanks,
Mark -
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. -
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 -
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
Maybe you are looking for
-
Error with windows 7 bootcamp drivers
Hello, I've installed Windows 7 via bootcamp and it's working fine, the only issue is that I don't have sound and I read that to get that I should install the drivers from my OS disc. The problem is that when I insert the disc and run the setup file,
-
How to change last page header under TOP-OF-PAGE in a report
hi, there are 20 pages in the report for which same header is diplayed for 20 pages by using follow. TOP-OF-PAGE. PERFORM write_doc_header. now the requirement is to change the last page heading. for this i've another perform statement. so plz let me
-
Material - UoM Pair issue in SRM Portal - shopping cart
Hello Experts, When we try to add Pair type material in shopping cart in SRM Sandbox Portal (Material no: 11100000000111) , it is throwing error as " Incomplete items in catalog. Only complete items were transferred" in checkout screen and item is no
-
Need to do two operations, from two sub vendors. After completion of on work from one sub vendor, that should go directly to second vendor for second operation. then retur back to us. how to do?
-
The address for my broadband is wrong.
The address for my broadband, on my broadband account, is wrong. I moved here about two years ago. The over all account information is right, but the address under my broadband is still showing my old address. How do I fix this?