I downloaded a sample from https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/speech for Java with the same exact code.
I did everything the way it supposed to be and it worked for a while " I have Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file " , and then idk what happen to it, started showing me this exception
com.google.api.gax.rpc.UnavailableException: io.grpc.StatusRuntimeException: UNAVAILABLE: Credentials failed to obtain metadata
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.speech;
// [START speech_transcribe_infinite_streaming]
import com.google.api.gax.rpc.ClientStream;
import com.google.api.gax.rpc.ResponseObserver;
import com.google.api.gax.rpc.StreamController;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.StreamingRecognitionConfig;
import com.google.cloud.speech.v1.StreamingRecognitionResult;
import com.google.cloud.speech.v1.StreamingRecognizeRequest;
import com.google.cloud.speech.v1.StreamingRecognizeResponse;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.TargetDataLine;
public class InfiniteStreamRecognize {
// Creating shared object
private static volatile BlockingQueue<byte[]> sharedQueue = new LinkedBlockingQueue();
private static TargetDataLine targetDataLine;
private static int BYTES_PER_BUFFER = 6400; // buffer size in bytes
public static void main(String... args) {
try {
infiniteStreamingRecognize();
} catch (Exception e) {
System.out.println("Exception caught: " + e);
}
}
/** Performs infinite streaming speech recognition */
public static void infiniteStreamingRecognize() throws Exception {
// Microphone Input buffering
class MicBuffer implements Runnable {
#Override
public void run() {
System.out.println("Start speaking...Press Ctrl-C to stop");
targetDataLine.start();
byte[] data = new byte[BYTES_PER_BUFFER];
while (targetDataLine.isOpen()) {
try {
int numBytesRead = targetDataLine.read(data, 0, data.length);
if ((numBytesRead <= 0) && (targetDataLine.isOpen())) {
continue;
}
sharedQueue.put(data.clone());
} catch (InterruptedException e) {
System.out.println("Microphone input buffering interrupted : " + e.getMessage());
}
}
}
}
// Creating microphone input buffer thread
MicBuffer micrunnable = new MicBuffer();
Thread micThread = new Thread(micrunnable);
ResponseObserver<StreamingRecognizeResponse> responseObserver = null;
try (SpeechClient client = SpeechClient.create()) {
ClientStream<StreamingRecognizeRequest> clientStream;
responseObserver =
new ResponseObserver<StreamingRecognizeResponse>() {
ArrayList<StreamingRecognizeResponse> responses = new ArrayList<>();
public void onStart(StreamController controller) {}
public void onResponse(StreamingRecognizeResponse response) {
responses.add(response);
StreamingRecognitionResult result = response.getResultsList().get(0);
// There can be several alternative transcripts for a given chunk of speech. Just
// use the first (most likely) one here.
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
System.out.printf("Transcript : %s\n", alternative.getTranscript());
}
public void onComplete() {
System.out.println("Done");
}
public void onError(Throwable t) {
System.out.println(t);
}
};
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
RecognitionConfig recognitionConfig =
RecognitionConfig.newBuilder()
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
.setLanguageCode("en-US")
.setSampleRateHertz(16000)
.build();
StreamingRecognitionConfig streamingRecognitionConfig =
StreamingRecognitionConfig.newBuilder().setConfig(recognitionConfig).build();
StreamingRecognizeRequest request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build(); // The first request in a streaming call has to be a config
clientStream.send(request);
try {
// SampleRate:16000Hz, SampleSizeInBits: 16, Number of channels: 1, Signed: true,
// bigEndian: false
AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);
DataLine.Info targetInfo =
new Info(
TargetDataLine.class,
audioFormat); // Set the system information to read from the microphone audio
// stream
if (!AudioSystem.isLineSupported(targetInfo)) {
System.out.println("Microphone not supported");
System.exit(0);
}
// Target data line captures the audio stream the microphone produces.
targetDataLine = (TargetDataLine) AudioSystem.getLine(targetInfo);
targetDataLine.open(audioFormat);
micThread.start();
long startTime = System.currentTimeMillis();
while (true) {
long estimatedTime = System.currentTimeMillis() - startTime;
if (estimatedTime >= 55000) {
clientStream.closeSend();
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build();
startTime = System.currentTimeMillis();
} else {
request =
StreamingRecognizeRequest.newBuilder()
.setAudioContent(ByteString.copyFrom(sharedQueue.take()))
.build();
}
clientStream.send(request);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}
// [END speech_transcribe_infinite_streaming]
I expect to speak and get recognized " I don't know why it does this " although it was working well .. can anyone help >> thank you in advance;
Some one help me this this exception when send object from server to client
it is NotSerializableException <<
and i try to solve the error and implements the interface Serializable and same exception >> >>> >
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Haz
*/
public class Server {
boolean isRunning = true;
public static final int Port = 500;
public static final String Address = "127.0.0.1";
ObjectOutputStream outToClient;
Socket Client;
ArrayList<ConnectionHandler> Handlers;
HashSet<Socket> Callers;
public Server() throws IOException {
ServerSocket socketSer = new ServerSocket(500);
ExecutorService service = Executors.newFixedThreadPool(50);
Handlers = new ArrayList<>();
Callers = new HashSet<>();
while (isRunning) {
Client = socketSer.accept();
System.out.println("Client Connect on Sever");
ConnectionHandler handler = new ConnectionHandler(Client,socketSer);
Handlers.add(handler);
Callers.add(Client);
SendConnectToAll(Handlers);
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
new Server();
}
private void SendConnectToAll(ArrayList<ConnectionHandler> Handlers){
try {
outToClient = new ObjectOutputStream(Client.getOutputStream());
outToClient.writeObject(Handlers);
outToClient.flush();
outToClient.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Haz
*/
public class SocketClient {
Socket Client;
ObjectInputStream inputFromServer;
public SocketClient(String Address,int Port) {
try {
Client = new Socket(Address,Port);
} catch (IOException ex) {
Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
}
new Thread(new Runnable(){
#Override
public void run() {
Object temp =null;
try {
inputFromServer = new ObjectInputStream(Client.getInputStream());
temp =inputFromServer.readObject();
while((temp)!=null){
temp = inputFromServer.readObject();
System.out.println(temp);
}
inputFromServer.close();
} catch (IOException ex) {
Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SocketClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
}
}
and class ConnectionHandler it is empty but i implements
public class ConnectionHandler implements Runnable,Serializable {
private Socket Client;
private ServerSocket Server;
public ConnectionHandler(Socket Client, ServerSocket Server) {
this.Client = Client;
this.Server = Server;
}
ConnectionHandler is not serializable because it contains references to Socket and ServerSocket, which are not serializable. You would have to write your own serialization and deserialization methods to make it serializable.
However, it doesn't make sense to make it serializable anyway, since it doesn't have any serializable data in it to transmit over the network.
I am trying to communicate client and server in one project where my client and server both started in main() of my project having two different threads but when client try to call the answer_is function of server side it will show the below exception. When I run the client and server combined in one project I got the error
xception in thread "Thread-2" java.lang.InstantiationError:
org.apache.xmlrpc.XmlRpcRequest
at org.apache.xmlrpc.XmlRpcRequestProcessor.decodeRequest(XmlRpcRequestProcessor.java:82)
at org.apache.xmlrpc.XmlRpcWorker.execute(XmlRpcWorker.java:143)
at org.apache.xmlrpc.XmlRpcServer.execute(XmlRpcServer.java:139)
at org.apache.xmlrpc.XmlRpcServer.execute(XmlRpcServer.java:125)
at org.apache.xmlrpc.WebServer$Connection.run(WebServer.java:761)
at org.apache.xmlrpc.WebServer$Runner.run(WebServer.java:642)
at java.lang.Thread.run(Thread.java:745)
Exception in thread "Thread-3" java.lang.InstantiationError: org.apache.xmlrpc.XmlRpcRequest
at org.apache.xmlrpc.XmlRpcRequestProcessor.decodeRequest(XmlRpcRequestProcessor.java:82)
at org.apache.xmlrpc.XmlRpcWorker.execute(XmlRpcWorker.java:143)
at org.apache.xmlrpc.XmlRpcServer.execute(XmlRpcServer.java:139)
at org.apache.xmlrpc.XmlRpcServer.execute(XmlRpcServer.java:125)
at org.apache.xmlrpc.WebServer$Connection.run(WebServer.java:761)
at org.apache.xmlrpc.WebServer$Runner.run(WebServer.java:642)
at java.lang.Thread.run(Thread.java:745)
JavaClient: org.apache.xmlrpc.XmlRpcException: Failed to create input stream: Unexpected end of file from server
Here is my code for Project 1 having client and server
Main Class
package serverclienttest;
/**
*
* #author root
*/
public class ServerclientTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
ServerThread serverthread = new ServerThread();
Thread t = new Thread(serverthread);
t.start();
ClientThread clientthread = new ClientThread();
Thread t1 = new Thread(clientthread);
t1.start();
} catch (Exception exception) {
System.err.println("WebClientServer: " + exception);
}
}
}
ClientSide
package serverclienttest;
import java.net.URL;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;
import java.util.*;
import java.io.*;
import java.net.*;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcClient;
import java.util.*;
import java.io.*;
/**
*
* #author root
*/
public class ClientThread implements Runnable{
public void run()
{
try {
// XmlRpcClient server = new XmlRpcClient("http://localhost/RPC2");
XmlRpcClient client = new XmlRpcClient();
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://localhost:5300/RPC2"));
config.setEnabledForExtensions(true);
//Vector params = new Vector();
/* Hashtable params = new Hashtable();
params.put(1, 1);
params.put(2, 2);*/
Object[] testclass = new Object[]{1,2};
client.setConfig(config);
int result = (Integer) client.execute("sample.sum", testclass);
System.out.print("Client Executed");
int sum = ((Integer) result).intValue();
System.out.println("The sum is: "+ sum);
} catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
}
}
Server Side
public class ServerThread {
public ServerThread() {
System.out.println("Handler registered as answer_is");
}
public Integer sum(int x, int y){
return new Integer(x+y);
}
public void run()
{
try {
System.out.println("Attempting to start XML-RPC Server...");
WebServer server = new WebServer(5300);
server.addHandler("sample", new ServerThread());
server.start();
System.out.println("Started successfully.");
System.out.println("Accepting requests. (Halt program to stop.)");
}
catch (Exception exception){
System.err.println("JavaServer: " + exception);
}
}
But when i wrote server side in another project and run it , it will work fine so plz tell me why client and server not run in same project
"Unexpected end of file from Server" implies that the server accepted and closed the connection without sending a response. It's possible that the system is too busy to handle the request, or that there's a bug that randomly drops connections.
In your ServerclientTest class, you are invoking:
ServerThread serverthread = new ServerThread();
Thread t = new Thread(serverthread);
without implementing Runnable. Try changing the class signature as below:
public class ServerThread implements Runnable
//Server Side This will work for me
import java.io.FileWriter;
import java.io.IOException;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcServer;
import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
import org.apache.xmlrpc.webserver.WebServer;
/**
*
* #author root
*/
public class ServerThread implements Runnable {
private static final String fileName = "/tmp/sample.txt";
/** Default port. */
private static final int defaultPort = 7777;
/** Password. */
private static final String password = "2isAnOddPrime";
/** Handler name. */
private static final String handlerName = "sample";
public Integer sum(int x, int y) {
return new Integer(x + y);
}
public ServerThread()
{
}
public ServerThread(int port) throws InterruptedException, XmlRpcException, IOException {
System.out.println("Handler registered as answer_is");
// Thread.sleep(5000);
WebServer webServer = new WebServer(port);
XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();
PropertyHandlerMapping phm = new PropertyHandlerMapping();
phm.addHandler(handlerName,ServerThread.class);
xmlRpcServer.setHandlerMapping(phm);
XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl)xmlRpcServer.getConfig();
serverConfig.setEnabledForExtensions(true);
serverConfig.setContentLengthOptional(false);
webServer.start();
System.out.println("Done.\nListening on port: " + port);
xmlRpcServer.setHandlerMapping(phm);
}
private void writeToFile(long prime)
{
try
{
FileWriter out = new FileWriter(fileName);
out.write(prime + "");
out.close();
}
catch (Exception e)
{
System.err.println("Could not write " + prime + " to file " + fileName + "\nReason: " + e.getMessage());
}
}
public void run() {
try {
int port = 5300;
new ServerThread(port);
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Reinstating this question with a bounty! I need an example that stays online, like a real instant messenger! It needs to always be ready to receive or send a message to an arbitrary address over an arbitrary port, using TCP. The program must not quit after sending/receiving a message.
Bounty goes to whoever can give the best example of a real, usable instant messenger.
Looking online, all resources I found are either useless tutorials, dead threads, dead tutorials, ancient examples, or tell the programmer to use external APIs. How can I create a basic instant messenger from the ground up, only using Java SE?
There must be a way to do this, and some sample code would be appreciated. It only needs to perform the simplest tasks: Check if a compatible client is online on another computer (IP will be provided by the user) and send a TCP packet to that client, which will receive and display its contents.
When this question was first asked and answered back in 2011, it was simply "Looking online, all resources I found are either useless
tutorials, dead threads, or tell the programmer to use external
APIs.". The provided links below met the criteria at the time. Further discussion follows in the comments.
First few Google results for "java socket chat":
http://cs.lmu.edu/~ray/notes/javanetexamples/
simple chatting program in java usings socket class
http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual/Lectures/chat-client-server.html
http://www.cise.ufl.edu/~amyles/tutorials/tcpchat/
http://ashishmyles.com/tutorials/tcpchat/index.html
Internet Archive link to fix missing Java source file downloads: https://web.archive.org/web/20150623102646/http://ashishmyles.com/tutorials/tcpchat/index.html
Or from "java 8 chat client":
https://gist.github.com/alex-zykov/b4052e3c1b6891081897
Many, many results following in the search. Pick one that suits your needs. You can even modify the Google search to only show results from the past year, if you wish.
I've done this when I was learning Java, something around 10 years ago. It works:
Constantes.java:
package jsc;
public interface Constantes {
public static final String MULTICAST_IP = "224.0.0.1";
public static final int MULTICAST_PORTA = 3333;
public static final String SEPARADOR = "[>>>]";
public static final int TAMANHO_MENSAGEM = 1024;
public static final long ESPERA = 3000;
public static final String ESTOUONLINE = "EstouOnline";
public static final String DESCONECTANDO = "Desconectando";
public static final String PRIVADO = "Privado";
}
ControladorThread.java
package jsc;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;
public class ControladorThread extends Thread implements Constantes{
private MulticastSocket mcSocket;
private Main main;
private Vector<Usuario> listaUsuarios; // lista de usuários ativos
public ControladorThread(Main main){
super("ReceptoraThread_" + main.getNick());
listaUsuarios = new Vector<Usuario>();
listaUsuarios.add(new Usuario(main.getNick(), new Date().getTime()));
this.main = main;
try{
mcSocket = new MulticastSocket(MULTICAST_PORTA);
mcSocket.joinGroup(InetAddress.getByName(MULTICAST_IP));
} catch(IOException e){
e.printStackTrace();
}
}
public void run(){
while(true){
try{
byte[] buffer = receberPacote();
processar(buffer);
removerUsuariosOciosos();
atualizarListaUsuarios();
} catch(IOException e){
e.printStackTrace();
}
}
}
public byte [] receberPacote() throws IOException{
byte[] buffer = new byte[TAMANHO_MENSAGEM];
DatagramPacket pacote = new DatagramPacket(buffer, buffer.length);
mcSocket.receive(pacote);
return buffer;
}
public void processar(byte[] buffer){
String mensagem = new String(buffer);
mensagem = mensagem.trim();
StringTokenizer tokens = new StringTokenizer(mensagem, SEPARADOR);
String t1 = tokens.nextToken();
String t2 = tokens.nextToken();
if(t1.equals(ESTOUONLINE))
atualizarEstadoUsuario(t2);
else if(t1.equals(DESCONECTANDO))
desconectarUsuario(t2);
else if(t1.equals(PRIVADO)){
String t3 = tokens.nextToken();
String t4 = tokens.nextToken();
if(t3.equals(main.getNick())){
receberMensagemPrivada(t2, t4);
}
}
else
main.setTextoEntrada(t1 + " diz: " + t2);
}
public void receberMensagemPrivada(String deUsuario, String mensagem){
main.abrirChatPrivado(main.getNick(), deUsuario, mensagem);
}
public boolean atualizarEstadoUsuario(String nomeUsuario){
int pos;
for(Iterator i = listaUsuarios.iterator(); i.hasNext(); ){
Usuario uAux = (Usuario) i.next();
if(uAux.getNome().equals(nomeUsuario)){
pos = listaUsuarios.indexOf(uAux);
listaUsuarios.remove(uAux);
uAux.setTempoInicio(new Date().getTime());
listaUsuarios.add(pos, uAux);
return true;
}
}
listaUsuarios.add(new Usuario(nomeUsuario, new Date().getTime()));
return false;
}
public void removerUsuariosOciosos(){
Usuario usuario = null;
for(Iterator i = listaUsuarios.iterator(); i.hasNext(); ){
usuario = (Usuario) i.next();
if(new Date().getTime() - usuario.getTempoInicio() > ESPERA){
desconectarUsuario(usuario.getNome());
i = listaUsuarios.iterator();
}
}
}
public void desconectarUsuario(String nomeUsuario){
for(Iterator i = listaUsuarios.iterator(); i.hasNext(); ){
Usuario uAux = (Usuario) i.next();
if(uAux.getNome().equals(nomeUsuario)){
i.remove();
break;
}
}
}
public void atualizarListaUsuarios(){
Vector<String> sVector = new Vector<String>();
Usuario uAux = null;
System.out.println("\nOnline: ");
for(Iterator i = listaUsuarios.iterator(); i.hasNext(); ){
uAux = (Usuario) i.next();
System.out.print( uAux.getNome() + " ");
sVector.add(uAux.getNome());
}
main.setUsuariosOnline(sVector);
}
private class Usuario{
private String nome;
private long tempoInicio;
public Usuario(){}
public Usuario(String nome, long tempoInicio){
this.nome = nome;
this.tempoInicio = tempoInicio;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public long getTempoInicio() {
return tempoInicio;
}
public void setTempoInicio(long tempoInicio) {
this.tempoInicio = tempoInicio;
}
}
public void sair(){
try {
mcSocket.leaveGroup(InetAddress.getByName(MULTICAST_IP));
mcSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EstouOnlineThread.java
package jsc;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class EstouOnlineThread extends Thread implements Constantes{
private MulticastSocket mcSocket;
private String nick;
private byte[] buffer;
public EstouOnlineThread(String nick){
super("EstouOnlineThread_" + nick);
this.nick = nick;
try {
mcSocket = new MulticastSocket();
} catch(IOException e) {
e.printStackTrace();
}
}
public void run(){
String saida = ESTOUONLINE + SEPARADOR + nick;
buffer = saida.getBytes();
while(true){
try{
DatagramPacket estouOnline = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(MULTICAST_IP), MULTICAST_PORTA);
mcSocket.send(estouOnline);
System.out.println(saida);
sleep(ESPERA);
}
catch(InterruptedException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
MensagemPrivadaFrame.java
package jsc;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
public class MensagemPrivadaFrame extends Frame implements Constantes{
private static final long serialVersionUID = 1L;
private TextArea entrada;
private TextField saida;
private String nomeJanela;
private String nick;
private String paraUsuario;
private MulticastSocket mcSocket;
private ActionListener saidaListener;
private WindowAdapter frameListener;
private boolean estouVivo; // indica que a janela ainda está ativa
public MensagemPrivadaFrame(String nick, String paraUsuario){
super("JSC - Chat com " + paraUsuario);
setIconImage(Toolkit.getDefaultToolkit().getImage("icone.4"));
this.nick = nick;
this.paraUsuario = paraUsuario;
this.nomeJanela = nick + paraUsuario;
try {
mcSocket = new MulticastSocket();
} catch (IOException e) {
e.printStackTrace();
}
iniciarComponentes();
estouVivo = true;
}
public void setNomeJanela(String nomeJanela){
this.nomeJanela = nomeJanela;
}
public String getNomeJanela(){
return nomeJanela;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public boolean estouVivo(){
return estouVivo;
}
public void iniciarComponentes(){
saidaListener = new ActionListener(){
public void actionPerformed(ActionEvent e){
TextField origem = (TextField) e.getSource();
enviarMensagem(origem.getText());
entrada.append("\n(" + nick + " diz) " + origem.getText());
origem.setText("");
}
};
frameListener = new WindowAdapter(){
public void windowClosing(WindowEvent e){
estouVivo = false;
dispose();
}
};
entrada = new TextArea("[JSC] Bate papo privado entre " + nick + " e " + paraUsuario + "\n");
entrada.setEditable(false);
saida = new TextField();
saida.addActionListener(saidaListener);
addWindowListener(frameListener);
setLayout(new BorderLayout());
int x = (int) (Math.random() * 500);
int y = (int) (Math.random() * 500);
setBounds(x, y, 400, 300);
System.out.println(x + " " + y);
add("Center", entrada);
add("South", saida);
setVisible(true);
saida.requestFocus();
}
public void setTextoEntrada(String texto){
entrada.append("\n" + texto);
entrada.setCaretPosition(entrada.getText().length());
}
public void enviarMensagem(String mensagem){
try{
mensagem = PRIVADO + SEPARADOR + nick + SEPARADOR + paraUsuario + SEPARADOR + mensagem;
byte[] bMensagem = mensagem.getBytes();
DatagramPacket pacote = new DatagramPacket(bMensagem, bMensagem.length, InetAddress.getByName(MULTICAST_IP), MULTICAST_PORTA);
mcSocket.send(pacote);
}
catch(UnknownHostException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}
Main.java
package jsc;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.ScrollPane;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
public class Main extends Frame implements Constantes{
private static final long serialVersionUID = 1L;
private TextArea entrada;
private TextField saida;
private JList usuariosOnline;
private ScrollPane usuariosOnlineScroll;
private WindowAdapter mainListener;
private ActionListener saidaListener;
private MouseAdapter listListener;
private MulticastSocket mcSocket; // soquete para multicasting
private Vector<String> listaUsuariosOnline; // lista com os nomes de usuários online
private Vector<MensagemPrivadaFrame> listaJanelasAbertas; // janelas de conversação privadas abertas
private String nick; // nome do usuário no chat
public void setNick(String nick){
this.nick = nick;
}
public String getNick(){
return nick;
}
public Main(String nick){
super("Java Socket Chat [" + nick + "]");
setIconImage(Toolkit.getDefaultToolkit().getImage("icone.1"));
this.nick = nick;
listaUsuariosOnline = new Vector<String>();
listaUsuariosOnline.add(nick);
listaJanelasAbertas = new Vector<MensagemPrivadaFrame>();
try{
mcSocket = new MulticastSocket();
}
catch(IOException e){
e.printStackTrace();
}
iniciarComponentes();
new EstouOnlineThread(nick).start();
new ControladorThread(this).start();
}
public void iniciarComponentes(){
mainListener = new WindowAdapter(){
public void windowClosing(WindowEvent e){
sair();
}
};
saidaListener = new ActionListener(){
public void actionPerformed(ActionEvent e){
TextField origem = (TextField) e.getSource();
enviarMensagem(origem.getText());
origem.setText("");
}
};
listListener = new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if( e.getClickCount() >= 2 ){
// abrir a janela para mensagens privadas e passar o id do usuário
JList jlAux = (JList) e.getSource();
String paraUsuario = (String) jlAux.getSelectedValue();
abrirChatPrivado(nick, paraUsuario, null);
}
}
};
usuariosOnline = new JList(listaUsuariosOnline);
usuariosOnline.setSize(new Dimension(60, 280));
usuariosOnlineScroll = new ScrollPane();
usuariosOnlineScroll.add(usuariosOnline);
entrada = new TextArea("Olá " + nick);
entrada.setEditable(false);
entrada.setSize(300,280);
saida = new TextField();
saida.addActionListener(saidaListener);
usuariosOnline.addMouseListener(listListener);
usuariosOnline.setMinimumSize(new Dimension(60, 250));
addWindowListener(mainListener);
setSize(400, 300);
setLayout(new BorderLayout());
add("North", new JLabel("Java Socket ChatO"));
add("Center", entrada);
add("South", saida);
add("East", usuariosOnlineScroll);
setVisible(true);
requestFocus();
}
public void enviarMensagem(String mensagem){
try{
mensagem = nick + SEPARADOR + mensagem;
byte[] bMensagem = mensagem.getBytes();
DatagramPacket pacote = new DatagramPacket(bMensagem, bMensagem.length, InetAddress.getByName(MULTICAST_IP), MULTICAST_PORTA);
mcSocket.send(pacote);
}
catch(UnknownHostException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
private void desconectando(){
try{
String mensagem = "Desconectando" + SEPARADOR + nick;
byte[] bMensagem = mensagem.getBytes();
DatagramPacket pacote = new DatagramPacket(bMensagem, bMensagem.length, InetAddress.getByName(MULTICAST_IP), MULTICAST_PORTA);
mcSocket.send(pacote);
}
catch(UnknownHostException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
public void abrirChatPrivado(String nick, String paraUsuario, String mensagem){
removerJanelasInativas();
if(nick.equals(paraUsuario)){
JOptionPane.showMessageDialog(null, "Você não pode abrir um janela de conversação para você mesmo!", "Burro!", JOptionPane.ERROR_MESSAGE);
return;
}
String nome = nick + paraUsuario;
MensagemPrivadaFrame janela = null;
for(Iterator i = listaJanelasAbertas.iterator(); i.hasNext();){
janela = (MensagemPrivadaFrame) i.next();
if(nome.equals(janela.getNomeJanela())){
System.out.println(nick + " - " + janela.getNomeJanela() + " - " + janela.toString());
janela.setTextoEntrada("(" + paraUsuario + " diz) " + mensagem);
//janela.requestFocus();
return;
}
}
janela = new MensagemPrivadaFrame(nick, paraUsuario);
if(mensagem != null)
janela.setTextoEntrada("(" + paraUsuario + " diz) " + mensagem);
listaJanelasAbertas.add(janela);
//janela.requestFocus();
}
public void removerJanelasInativas(){
MensagemPrivadaFrame janela = null;
for(Iterator i = listaJanelasAbertas.iterator(); i.hasNext(); ){
janela = (MensagemPrivadaFrame) i.next();
if( !janela.estouVivo()){
i.remove();
}
}
}
public void setTextoEntrada(String texto){
entrada.append("\n" + texto);
entrada.setCaretPosition(entrada.getText().length());
}
public void setUsuariosOnline(Vector<String> listaUsuariosOnline){
usuariosOnline.setListData(listaUsuariosOnline);
}
public void sair(){
desconectando();
dispose();
System.exit(0);
}
public static void main(String args[]){
String nick = JOptionPane.showInputDialog("Digite seu nome (max. 20 caracteres): ");
if(nick != null && !nick.equals("")){
if(nick.length() > 20)
nick = nick.substring(0, 20);
new Main(nick);
}
else
JOptionPane.showMessageDialog(null, "É necessário informar um nome para entrar no bate-papo");
//System.exit(0);
}
}
Nowadays I'm not proud of the code, but it really works.
Edit:
As some have suggested, I've made some code improvements (refactoring) and post the project on GitHub: https://github.com/jaumzera/javasocketchat
Hm, I was tempted to direct you to a java implementation of a server implementing imap protocol (eg. gavamail). But this, of cources, might also qualify as "old" code and for sure would kill your expectation (for being a non-standard solution). Nevertheless it is a proper reference fulfilling your (terse) specification.
What do we have?
We need a solution that should be in java.
It must implement an basic instant messaging system.
The later is problematic as it covers a really broad range of functionality. But "basic" seem to allow for a minimum solution.
So what is a minimum instant messaging system? Let's try with the following:
a client that is posting and retrieving messages.
a server that is storing posted messages for (later) retrieval
We also would need a policy of how a client would identify a proper server. Most trivial solution for the later aspect is using a "central" server with a well-known address. For more complex cases we would need to have the server and/or client functionality distributed across several instances and devise a scheme or policy for identifying the proper instance(s) for communication.
We leave out more complex semantics like having different users or messages being related to a system of categories or tags.
Now, we are down to having two components:
A server implementing two entry points:
POST_MESSAGE
receive a mesage form a client and store it for later retrieval
This immediatley is asking the question of where to store such messages (in a database or filesystem for persistency or simply within memory for a "messages live as long as the server is up" semantics)
LOOKUP_MESSAGE
select a suitable message from the stored ones (preferrably an unread one) and return to caller.
This could also return a set of messages (but think of restricting such set for cases where a caller has a severe backlog of messages)
It might be necessary to keep track of the messages already having been read, either by marking the messages or by maintaining seen status at the client. This could even be as simple as keeping time or ordinal of last message seen and send this information along with the LOOKUP_MESSAGE request.
A client needs to interact with a user on one hand and the service on the other hand.
It will take gat a new message from the user (likely on explicit request (e.g. send button) and call the POST_MESSAGE service at the related server.
It also will (likely regularly, could also be on explicit request (e.g. user is starting client)) poll the server for new messages. (Alternatively, you could devise a separate notification service that is used by the server to notify the client of new messages. What suits your "needs" is beyond your question.)
That's it.
So any example of a TCP based client/server application will form a perfect starting point for a straight implementation.
I should also mention that you could cut the specification logic within the client and delegate user interaction to a standard browser and implement the client application logic into a (web-)server instance (together or separate from the server part). Nevertheless, you still will have both (client/server) logical functionality according to above minimum specification.
Another aspect you should be aware of:
With some comments you mentioned "host" and "guest" attributions available in current messenger examples. This actually is a logical structure of a tagging system provided with those messengers. The messages are still sent from a client to a server and then being retrieved by other clients. Whether a client can see a message is determined by the client being eligible to the specific tag. E.g posting a message to a contact from yours (user b) just tags the message with the tag "for_user_b" and as such it is only visible to the poster and anybody that is also allowed to read "for_user_b" tag messages (user b in our example). So, please be aware that the logical structure of a messaging system is determined by the access and distribution policy and not by the physical distribution structure!
I am not even sure if this question is still being used or what but I liked the task and I thought:
why not?
Here is my implementation, as simple as it gets but without forgetting fundamental parts.
Written in pure Java, makes use of, among the rest, Sockets, Threads and SynchronizedList:
SimpleChat.java (Main)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SimpleChat {
private static boolean isRunning = true;
private static Sender sender;
private static Receiver receiver;
public static void main(String[] args) throws IOException {
if(args.length < 3){
showUsage();
}
try {
receiver = new Receiver(Integer.parseInt(args[1]));
sender = new Sender(args[0], args[2], Integer.parseInt(args[3]));
} catch (InterruptedException e) {
showUsage();
}
// Read user input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Chat started. Type '\\exit' to quit.");
while(isRunning) {
String input = br.readLine();
if(input.equals("\\exit")){
receiver.stop();
sender.stop();
isRunning = false;
} else {
sender.sendMessage(input);
}
}
}
static void showUsage(){
System.out.println("Usage: java SimpleChat.java listening_port target_IP target_port");
System.exit(1);
}
}
Receiver.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Receiver {
private boolean isRunning = true;
public Receiver(int listeningPort) throws IOException {
Runnable receiverT = new Runnable() {
public void run() {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(listeningPort);
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(isRunning) {
try {
System.out.println(in.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
new Thread(receiverT).start();
}
public void stop(){
isRunning = false;
}
}
Sender.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class Sender {
private boolean isRunning = true;
private volatile List<String> msgs;
public Sender(String username, String targetIP, int targetPort) throws InterruptedException, UnknownHostException, IOException {
msgs = Collections.synchronizedList(new ArrayList<String>());
Runnable senderT = new Runnable() {
public void run() {
try {
Socket socket = new Socket(targetIP, targetPort);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while(isRunning) {
synchronized(msgs){
Iterator<String> it = msgs.iterator();
while(it.hasNext()){
out.println(username + ": " + it.next());
}
// Clear messages to send
msgs.clear();
}
}
out.close();
socket.close();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
new Thread(senderT).start();
}
public void stop(){
isRunning = false;
}
public void sendMessage(String msg){
synchronized(msgs){
msgs.add(msg);
}
}
}
As the 'showUsage()' says, use this program as follows:
java SimpleChat.java username listening_port target_ip target_port
Example:
java SimpleChat.java Supuhstar 1234 127.0.0.1 1234
[To talk to yourself]
I think you should clarify some details regarding what exactly you mean by a "basic instant messaging program" and what your objectives actually are regarding this project.
In a 2011 comment, you mentioned that there should be no "central hub", but in a more recent comment, you say that you would like something more in line with Skype or iMessage, where users do not have to know which peer is the server... It is technically possible (using protocols such as mdns, dlna or ssdp) for the program to transparently search the local network for potential existing server nodes and have it either connect to the server peer if there is one, or establish itself as a local server for other nodes to connect to it. That is for example how Apple iChat's Bonjour protocol used to work. This is however a rather complex solution to implement right, and is definitely not in line with what is done by current mass market messaging programs.
Also establishing direct peer-to-peer communication between users pose several practical issues (particularly because of firewalls and NAT, but there are also concerns of confidentiality and security). Most protocols therefore relay most messages through the central server, and negotiate a direct connection only for the purpose of file transfers and audio/video calls.
For all these reasons, unless you are looking merely for an example of local network communication between two hosts, you most certainly want two distinct programs: a server and a client.
Then, assuming my assumption is correct, there are two other questions that need to be clarified. First, do you have an actual reason to conceive the protocol by yourself, or would it be acceptable to rather implement an existing protocol (such as XMPP, IRC, SIMPLE... there are tons). Even though these protocols might looks highly complex at first, it is almost always possible to implement only a subset these protocol's features/messages. Designing a naive network protocol by yourself isn't that difficult, but there are tons of potential mistakes (mostly inefficiencies, incompleteness and other minor issues) that you will have to go through. Maybe that is indeed what you are specifically aiming for (that is, gaining experience at designing a network protocol from scratch), but unless it is so, you should seriously opt for implementing an existing protocol. Indeed, working with an existing protocol will not only avoid such design mistakes, but better yet, you will gain significant knowledge from how others (generally experienced protocol designers) actually resolved problems they met along the way. Using an existing protocol will also make it much easier and more interesting for you to develop that program, given that you will for example be able to test your client and server programs independently by connecting from/to an official client/server implementation. You will also be able to exploit exiting protocol-decoders in traffic sniffing tools in order to debug messages going through.
The second important question is how realistic you would like the server program to be, and most importantly in regard to persistance. Should the server maintain a persistant list of users and authenticate them? Should the server store a list of allowed contacts for each user? Should the server allow store messages aimed at a peer that is currently offline or that can't be reached at that exact moment? Real messaging server programs generally do such things, and though implementing such mechanisms isn't highly difficult, it is best considered early in the design of a program's architecture. For example, should you decide that these features are indeed desirable, then it might turn out to be much more interesting for you to immediately design your server around a persistant message queue engine, such as ActiveMQ...
I know this is not the examples you were asking for, but I still hope these thoughts may help you.
As said before, there is a lot of things that you need to put a real chat to work.
But i belive that you want something to start. And if you know the address and the port of the other "client" it is easy.
Extreme simple "chat" implementation
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
public class SimpleChat {
protected boolean running = true;
protected int port;
private Thread server;
public static void main(String... arg) {
//create 2 clients in the localhost to test
SimpleChat app1 = new SimpleChat(8989);
SimpleChat app2 = new SimpleChat(8988);
app1.sendMessage("localhost", 8988, "Message from app1 to app2");
app2.sendMessage("localhost", 8989, "Message from app2 to app1");
System.exit(0); // ugly way to kill the threads and exit
}
public SimpleChat(int port) {
this.port = port;
start();
}
public void start() {
server = new Thread(new Server());
server.start();
}
public boolean sendMessage(String host, int port, String message) {
try {
//Connect to a server on given host and port and "send" the message
InetSocketAddress destination
= new InetSocketAddress(host, port);
Socket s = SocketFactory.getDefault().createSocket();
s.connect(destination);
OutputStream out = s.getOutputStream();
out.write(message.getBytes());
out.flush();
out.close();
s.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void messageRecived(String message) {
System.out.println("Message recived: " + message);
}
public void stop() {
this.running = false; // only stop after a socked connection
}
class Server implements Runnable {
public void run() {
try {
//Create a server socket to recieve the connection
ServerSocket ss = ServerSocketFactory.getDefault()
.createServerSocket(port);
while (running) {
Socket s = ss.accept();
InputStream in = s.getInputStream();
StringBuilder message = new StringBuilder();
int len;
byte[] buf = new byte[2048];
while ((len = in.read(buf)) > -1) {
if (len > 0) {
message.append(new String(buf, 0, len));
}
}
messageRecived(message.toString());
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
}
Using the ElementalHttpServer example class found here:
https://hc.apache.org/httpcomponents-core-4.3.x/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java
I am able to successfully receive post data, my goal is to convert the received post data into a string I can print. I've modified the HttpFileHandler as follows, using eneity.getContent() to get the inputStream, but i'm not sure how I can convert the inputStream into a String.
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
String target = request.getRequestLine().getUri();
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
InputStream inputStream = entity.getContent();
String str= inputStream.toString();
byte[] b3=str.getBytes();
String st = new String(b3);
System.out.println(st);
for(int i=0;i<b3.length;i++) {
System.out.print(b3[i]+"\t");
}
System.out.println("Incoming entity content (bytes): " + entityContent.length);
}
}
}
Thanks for any ideas
Here is simple console logging handler; it logs every request (not only POST) - both headers and payload:
package com.mycompany;
import org.apache.http.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
import org.omg.CORBA.Request;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by IntelliJ IDEA.
* User: Piotrek
* To change this template use File | Settings | File Templates.
*/
public class LoggingHandler implements HttpRequestHandler {
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
System.out.println(""); // empty line before each request
System.out.println(httpRequest.getRequestLine());
System.out.println("-------- HEADERS --------");
for(Header header: httpRequest.getAllHeaders()) {
System.out.println(header.getName() + " : " + header.getValue());
}
System.out.println("--------");
HttpEntity entity = null;
if (httpRequest instanceof HttpEntityEnclosingRequest)
entity = ((HttpEntityEnclosingRequest)httpRequest).getEntity();
// For some reason, just putting the incoming entity into
// the response will not work. We have to buffer the message.
byte[] data;
if (entity == null) {
data = new byte [0];
} else {
data = EntityUtils.toByteArray(entity);
}
System.out.println(new String(data));
httpResponse.setEntity(new StringEntity("dummy response"));
}
}
Registration of handler using org.apache.http.localserver.LocalTestServer (with ElementalHttpServer it is similar - you also have HttpRequestHandler implementation above):
public static void main(String[] args) throws Exception {
LocalTestServer server = new LocalTestServer(null, null);
try {
server.start();
server.register("/*", new LoggingHandler());
server.awaitTermination(3600 * 1000);
} catch (Exception e) {
e.printStackTrace();
} finally {
server.stop();
}
}