Java socket Json - java

UPDATED
There is my updated code after the response,
I have one problem, now, i didn't receive anything :
Problem :
Connexion cliente reçue.
Lancement du traitement de la connexion cliente
Exception in thread "Thread-1" java.lang.NullPointerException
at cuisine.TimeServer.onResponseReceived(TimeServer.java:85)
at cuisine.ClientProcessor.run(ClientProcessor.java:43)
at java.base/java.lang.Thread.run(Thread.java:844)
TimeServer: 85 : Callback
#Override
public void onResponseReceived(String response) {
// When the response is received from ClientProcessor
// this method is called (by ClientProcessor).
// Your response is the parameter String response.
callback.onResponse(response);
}
Client processor: 43 :
server.onResponseReceived(response);
One client can connect but i can't receive anything : Json or text.
There is my new Java Code :
Main.java :
import cuisine.TimeServer.OnResponseReceivedListener;
public class main implements OnResponseReceivedListener {
public static void main(String[] args) throws IOException {
String host = "192.168.1.21";
int port = 8080;
TimeServer ts = new TimeServer(host, port);
ts.open();
System.out.println("------------Connected ! ------------");
}
#Override
public void onResponse(String response) {
doSomethingWith(response);
System.out.println("REPONSE : ");
System.out.println(response);
}
private void doSomethingWith(String response) {
System.out.println("REPONSE : ");
System.out.println(response);
}
}
I don't really know how to use the response now, because the sysout "RESPONSE" is not in my console
TimeServer.java :
...
import cuisine.ClientProcessor.Server;
public class TimeServer implements Server {
public interface OnResponseReceivedListener {
void onResponse(String response);
}
private int port = 2345;
private String host = "127.0.0.1";
private ServerSocket server = null;
private boolean isRunning = true;
private OnResponseReceivedListener callback;
public TimeServer() {
try {
server = new ServerSocket(port, 100, InetAddress.getByName(host));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public TimeServer(String pHost, int pPort) {
host = pHost;
port = pPort;
try {
server = new ServerSocket(port, 100, InetAddress.getByName(host));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void open() {
Thread t =
new Thread(
new Runnable() {
public void run() {
while (isRunning == true) {
try {
Socket client = server.accept();
System.out.println("Connexion cliente reçue.");
ClientProcessor c = new ClientProcessor(client);
Thread t = new Thread(c);
// Don't forget to define the Server for ClientProcessor
c.addServer(TimeServer.this);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
server = null;
}
}
});
t.start();
}
#Override
public void onResponseReceived(String response) {
// When the response is received from ClientProcessor
// this method is called (by ClientProcessor).
// Your response is the parameter String response.
callback.onResponse(response);
}
public void addOnResponseReceivedListener(OnResponseReceivedListener listener) {
callback = listener;
}
public void removeOnResponseReceivedListener() {
callback = null;
}
public void close() {
isRunning = false;
}
}
ClientProcessor.java :
public class ClientProcessor implements Runnable {
public interface Server {
void onResponseReceived(String response);
}
private Socket sock;
private PrintWriter writer = null;
private BufferedInputStream reader = null;
public List<Dish> dish;
// Your server instance
private Server server;
public ClientProcessor(Socket pSock) {
this.sock = pSock;
}
public void run() {
System.err.println("Lancement du traitement de la connexion cliente");
boolean closeConnexion = false;
while (!sock.isClosed()) {
try {
writer = new PrintWriter(sock.getOutputStream());
reader = new BufferedInputStream(sock.getInputStream());
String response = read();
// report the response to TimeServer
server.onResponseReceived(response);
InetSocketAddress remote = (InetSocketAddress) sock.getRemoteSocketAddress();
String debug = "";
debug = "Thread : " + Thread.currentThread().getName() + ". ";
debug += "Demande de l'adresse : " + remote.getAddress().getHostAddress() + ".";
debug += " Sur le port : " + remote.getPort() + ".\n";
debug += "\t -> Commande reçue : " + response + "\n";
System.err.println("\n" + debug);
String toSend = "";
switch (response.toUpperCase()) {
case "ORDER":
toSend = "Dish";
break;
case "CLOSE":
toSend = "Communication terminée";
closeConnexion = true;
break;
default:
toSend = "Commande inconnu !";
break;
}
writer.write(toSend);
writer.flush();
if (closeConnexion) {
System.err.println("COMMANDE CLOSE DETECTEE ! ");
writer = null;
reader = null;
sock.close();
break;
}
} catch (SocketException e) {
System.err.println("LA CONNEXION A ETE INTERROMPUE ! ");
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void addServer(Server server) {
this.server = server;
}
private void removeServer() {
server = null;
}
// La méthode que nous utilisons pour lire les réponses
private String read() throws IOException {
String response = "";
int stream;
byte[] b = new byte[4096];
stream = reader.read(b);
response = new String(b, 0, stream);
return response;
}
}
Thanks,
Benjamin.

Update (updated Main.java)
Update No2 (Removed static methods from Main.java and use a Main object)
Edit: (removed previous answer about sockets)
This is the json response, now i want to use it in my main : on
another class in the same package.
Since you've stated that you are getting a response from client but you don't know how to manipulate it in your Main class then your issue is not about sockets.
A solution: Use callbacks:
ClientProcessor will report the response to TimeServer.
TimeServer will report that response to Main.
Make ClientProcessor aware of the server and report when the response is fetched.
public class ClientProcessor implements Runnable {
public interface Server {
void onResponseReceived(String response);
}
private Socket sock;
private PrintWriter writer = null;
private BufferedInputStream reader = null;
public List<Dish> dish;
// Your server instance
private Server server;
public ClientProcessor(Socket pSock) {
this.sock = pSock;
}
public void run() {
System.err.println("Lancement du traitement de la connexion cliente");
boolean closeConnexion = false;
while (!sock.isClosed()) {
try {
writer = new PrintWriter(sock.getOutputStream());
reader = new BufferedInputStream(sock.getInputStream());
String response = read();
// report the response to TimeServer
server.onResponseReceived(response);
InetSocketAddress remote = (InetSocketAddress) sock.getRemoteSocketAddress();
String debug = "";
debug = "Thread : " + Thread.currentThread().getName() + ". ";
debug += "Demande de l'adresse : " + remote.getAddress().getHostAddress() + ".";
debug += " Sur le port : " + remote.getPort() + ".\n";
debug += "\t -> Commande reçue : " + response + "\n";
System.err.println("\n" + debug);
String toSend = "";
switch (response.toUpperCase()) {
case "ORDER":
toSend = "Dish";
break;
case "CLOSE":
toSend = "Communication terminée";
closeConnexion = true;
break;
default:
toSend = "Commande inconnu !";
break;
}
writer.write(toSend);
writer.flush();
if (closeConnexion) {
System.err.println("COMMANDE CLOSE DETECTEE ! ");
writer = null;
reader = null;
sock.close();
break;
}
} catch (SocketException e) {
System.err.println("LA CONNEXION A ETE INTERROMPUE ! ");
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void addServer(Server server) {
this.server = server;
}
private void removeServer() {
server = null;
}
// La méthode que nous utilisons pour lire les réponses
private String read() throws IOException {
String response = "";
int stream;
byte[] b = new byte[4096];
stream = reader.read(b);
response = new String(b, 0, stream);
return response;
}
}
Now go to TimeServer and make it aware of Main (same procedure as before). You must also need to report the response to Main when its being received from ClientProcessor.
public class TimeServer implements Server {
public interface OnResponseReceivedListener {
void onResponse(String response);
}
private int port = 2345;
private String host = "127.0.0.1";
private ServerSocket server = null;
private boolean isRunning = true;
private OnResponseReceivedListener callback;
public TimeServer() {
try {
server = new ServerSocket(port, 100, InetAddress.getByName(host));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public TimeServer(String pHost, int pPort) {
host = pHost;
port = pPort;
try {
server = new ServerSocket(port, 100, InetAddress.getByName(host));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void open() {
Thread t =
new Thread(
new Runnable() {
public void run() {
while (isRunning == true) {
try {
Socket client = server.accept();
System.out.println("Connexion cliente reçue.");
Thread t = new Thread(new ClientProcessor(client));
// Don't forget to define the Server for ClientProcessor
t.addServer(TimeServer.this);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
server = null;
}
}
});
t.start();
}
#Override
public void onResponseReceived(String response) {
// When the response is received from ClientProcessor
// this method is called (by ClientProcessor).
// Your response is the parameter String response.
callback.onResponse(response);
}
public void addOnResponseReceivedListener(OnResponseReceivedListener listener) {
callback = listener;
}
public void removeOnResponseReceivedListener() {
callback = null;
}
public void close() {
isRunning = false;
}
}
Finaly, make your Main to listen to TimeServer and do something when it receives the response.
public class Main implements OnResponseReceivedListener {
public static void main(String[] args) {
Main application = new Main();
TimeServer ts = application.createTimeServer();
ts.addOnResponseReceivedListener(application);
ts.open();
System.out.println("------------Connected ! ------------");
}
#Override
public void onResponse(String response) {
doSomethingWith(response);
}
private void doSomethingWith(String response) {
// Your logic for the response here...
}
private TimeServer createTimeServer() {
String host = "192.168.43.178";
int port = 8080;
return new TimeServer(host, port);
}
}

Related

Multithread Server and Client with sockets in Java

I am trying to create for a university project a server / slave / client project.
The server should open 2 ports, one port will be for the connection of the slave and another port for the client.
I have setup 2 threads 1 for the client and another for the slave. The client should sent random numbers to server and server should forward randomly those numbers to slave instances. The slave should check if the current number exist on their list and if it's not available to store it, otherwise they should sent a message to server that the number already exist.
Then I created the client thread which consist of 2 threads, one for sending the numbers to server and another thread to read messages coming from the server.
There is something wrong with the code of the PrintWriter, I cannot make it to send the numbers to server when the code is inside the thread. If I move the code on the main and cancel the thread the messages are being sent without any issue.
What could be the issue for this?
Below is the current code from server (master) and the client.
public class Client {
private static final int NUMBERS = 50;
private static final int AMPLITUDE = 100;
private static int masterPort;
public Client(int port) {
this.masterPort = port;
}
public static void main(String[] args) throws IOException{
String serverHostname = "127.0.0.1";
System.out.println("Αναμονή για σύνδεση στον σέρβερ " + serverHostname + " στην πόρτα 30091.");
Socket echoSocket = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 18889);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Δεν μπορεί να πραγματοποιηθεί σύνδεση με τον σέρβερ: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + serverHostname);
System.exit(1);
}
ClientOut clientOut = new ClientOut(echoSocket);
clientOut.start();
ClientIn clientIn = new ClientIn(in);
clientIn.start();
in.close();
echoSocket.close();
}
public static class ClientOut extends Thread {
private PrintWriter out;
public ClientOut(Socket echoSocket) throws IOException {
this.out = new PrintWriter(echoSocket.getOutputStream(), true);
}
#Override
public void run() {
System.out.println("Ο client συνδέθηκε!");
Random rnd = new Random();
try {
for (int i=0; i<NUMBERS; i++) {
int num = rnd.nextInt(AMPLITUDE);
System.out.println(num);
out.println(num);
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
out.close();
}
}
public static class ClientIn extends Thread {
private BufferedReader in;
public ClientIn(BufferedReader in) {
this.in = in;
}
#Override
public void run() {
}
}
}
public class Master {
private int slavePort;
private int clientPort;
private SlaveThread slaveThread;
private ClientThread clientThread;
private boolean running = false;
public static int slaveConnected; // Slave connection counter
public Master(int slavePort, int clientPort) {
this.slavePort = slavePort;
this.clientPort = clientPort;
this.slaveConnected = 0;
public void startServer() {
try {
this.slaveThread = new SlaveThread(slavePort);
this.clientThread = new ClientThread(clientPort);
System.out.println( "Αναμονή για σύνδεση client / slave" );
slaveThread.start();
clientThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopServer() {
running = false;
this.slaveThread.interrupt();
this.clientThread.interrupt();
}
class SlaveThread extends Thread {
private ServerSocket slaveSocket;
SlaveThread(int slavePort) throws IOException {
this.slaveSocket = new ServerSocket(slavePort);
}
#Override
public void run() {
running = true;
while (running) {
try {
// Call accept() to receive the next connection
Socket slSocket = slaveSocket.accept();
System.out.println("Δημιουργήθηκε μια νέα σύνδεση Slave");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class ClientThread extends Thread {
private ServerSocket clientSocket;
ClientThread(int clientPort) throws IOException {
this.clientSocket = new ServerSocket(clientPort);
}
#Override
public void run() {
running = true;
while (running) {
try {
Socket clSocket = clientSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clSocket.getInputStream()));
System.out.println("Δημιουργήθηκε μια νέα σύνδεση Client");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Master server = new Master( 30091, 18889);
server.startServer();
// Automatically shutdown in 1 minute
try {
Thread.sleep( 60000 );
} catch(Exception e) {
e.printStackTrace();
}
server.stopServer();
}
I found the solution.
The Socket should be created on the Client Thread constructor and not to be passed as reference.
So the client should be
public class Client {
private static final int NUMBERS = 50;
private static final int AMPLITUDE = 100;
private static int masterPort;
public Client(int port) {
this.masterPort = port;
}
public static void main(String[] args) throws IOException{
String serverHostname = "127.0.0.1"; //Ορίζουμε την διεύθυνση που είναι ο σέρβερ
System.out.println("Αναμονή για σύνδεση στον σέρβερ " + serverHostname + " στην πόρτα 30091.");
ClientOut clientOut = new ClientOut(serverHostname);
clientOut.start();
ClientIn clientIn = new ClientIn(serverHostname);
clientIn.start();
}
public static class ClientOut extends Thread {
private Socket echoSocket;
private PrintWriter writer;
ClientOut(String serverHostname) throws IOException {
this.echoSocket = new Socket(serverHostname, 18889);
this.writer = new PrintWriter(echoSocket.getOutputStream(), true);;
}
#Override
public void run() {
System.out.println("Ο client συνδέθηκε!");
Random rnd = new Random();
try {
for (int i=0; i<NUMBERS; i++) {
int num = rnd.nextInt(AMPLITUDE);
System.out.println(num);
writer.println(num);
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
writer.close();
}
}

Java Socket consumes 100% CPU

I have a socket that is consuming 100% of the computer's CPU.
There are 150 clients sending messages to the server every 30 seconds unsynchronously.
Does anyone know how to solve this problem?
Below is my ServerSocket class
public class Servidor {
static ExecutorService es;
public static void main(String[] args) throws Exception {
es = Executors.newFixedThreadPool(150);
ServerSocket servidor = new ServerSocket(2010);
while (true) {
Socket soquete = null;
try {
System.out.println("Aguardando cliente: ");
soquete = servidor.accept();
System.out.println("Cliente Conectado: ");
es.execute(new Conexao(soquete));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The Conexao class (utility class) takes the string sent by the clients and saves it in the database.
Below my Conexao class
public class Conexao implements Runnable{
Socket soquete;
int contador = 0;
public Conexao(Socket soquete) {
super();
this.soquete = soquete;
}
#Override
public void run(){
BufferedReader in = null;
try{
in = new BufferedReader(new InputStreamReader(soquete.getInputStream()));
while (!in.ready()) {/*System.out.println("!in.ready()");*/}
String str =in.readLine();
System.out.println("Rodando Thread"+Thread.currentThread().getName() + " : texto: " + str);
}finally{
...
if(soquete != null){
try {
soquete.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
}
I solved the problem by removing part "while (!in.ready()) {/System.out.println("!in.ready()");/}" and creating a "Thread.sleep" at the end of the try block

How can I maintain two client sockets together using java

I want to create a class that contain two socket I.e socket for client1 and socket for client 2 so that they can chat together.
How can I achieve this.When i run above code i am getting stream corrupted exception .
My chat is not working. Can someone help me out ?
Here is my code .
This is client code for making socket request
Client.java
package customChat;
import java.net.*;
import java.io.*;
import java.util.*;
public class Client
{
private String notif = " *** ";
private ObjectInputStream sInput;
private ObjectOutputStream sOutput;
private Socket socket;
private String server, username;
private int port;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
private RemoteAccess access;
Client(String server, int port,RemoteAccess access ) {
this.server = server;
this.port = port;
this.access = access;
}
public boolean start()
{
try
{
socket = new Socket(server, port);
}
catch(Exception ec) {
display("Error connectiong to server:" + ec);
return false;
}
String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
display(msg);
try
{
sInput= new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException eIO) {
eIO.printStackTrace();
display("Exception creating new Input/output Streams in client: " + eIO);
return false;
}
new ListenFromServer().start();
try
{
sOutput.writeObject(access);
}
catch (IOException eIO) {
display("Exception doing login : " + eIO);
//disconnect();
return false;
}
return true;
}
private void display(String msg)
{
System.out.println(msg);
}
void sendMessage(RemoteAccess msg)
{
try
{
System.out.println("I am writing for :"+msg.getTo()+": msg "+msg.getMsg());
sOutput.writeObject(msg);
}
catch(IOException e) {
display("Exception writing to server: " + e);
}
}
private void disconnect() {
try {
if(sInput != null) sInput.close();
}
catch(Exception e)
{
e.printStackTrace();
}
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {
e.printStackTrace();
}
try{
if(socket != null) socket.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void sendFile()
{
int portNumber = 1502;
String serverAddress = "localhost";
Scanner scan = new Scanner(System.in);
System.out.println("Enter from ");
long from = scan.nextLong();
System.out.println("Enter to");
long to = scan.nextLong();
RemoteAccess access = new RemoteAccess(to,from,"hello");
Client client = new Client(serverAddress, portNumber,access);
if(!client.start())
return;
while(true)
{
System.out.println("Please enter msg:");
System.out.print("> ");
// read message from user
String msg = scan.nextLine();
System.out.println("Sending message");
client.sendMessage(new RemoteAccess(to,from,msg));
}
}
public static void main(String[] args)
{
sendFile();
}
class ListenFromServer extends Thread {
public void run()
{
System.out.println("i am in run method");
while(true)
{
System.out.println("i am in run method 2");
try
{
System.out.println("i am in run method 3");
RemoteAccess access = (RemoteAccess) sInput.readObject();
System.out.println("Message read by:"+access.getFrom());
if(access !=null)
{
System.out.println("Message is :"+access.getFrom());
}
}
catch(IOException e)
{
e.printStackTrace();
System.out.println("Excepion caught while listening from server :"+e);
display(notif + "Server has closed the connection: " + e + notif);
break;
}
catch(ClassNotFoundException e2) {
e2.printStackTrace();
}
}
}
}
}
Server.java
package customChat;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class Server {
private SimpleDateFormat sdf;
private int port;
private boolean keepGoing;
private String notif = " *** ";
public static ArrayList<ClientThread> al;
public Server(int port)
{
this.port = port;
sdf = new SimpleDateFormat("HH:mm:ss");
al = new ArrayList<ClientThread>();
}
public void start() {
keepGoing = true;
try
{
ServerSocket serverSocket = new ServerSocket(port);
while(keepGoing)
{
display("Server waiting for Clients on port " + port + ".");
Socket socket = serverSocket.accept();
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket);
Thread t1 =new Thread(t);
System.out.println("Connection initiated by:"+t.access.getFrom());
Server.al.add(t);
t1.start();
}
/*try {
serverSocket.close();
for(int i = 0; i < Server.al.size(); ++i) {
ClientThread tc = Server.al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {
ioE.printStackTrace();
}
}
}
catch(Exception e)
{
display("Exception closing the server and clients: " + e);
}*/
}
catch (IOException e) {
String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
display(msg);
}
}
/*protected void stop() {
keepGoing = false;
try {
new Socket("localhost", port);
}
catch(Exception e) {
}
}*/
// Display an event to the console
private void display(String msg) {
String time = sdf.format(new Date()) + " " + msg;
System.out.println(time);
}
public static void main(String[] args) {
// start server on port 1500 unless a PortNumber is specified
int portNumber = 1502;
// create a server object and start it
Server server = new Server(portNumber);
server.start();
}
}
ClientThread.java
package customChat;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
/*class ListClient
{
public static ArrayList<ClientThread> al=new ArrayList<>();;
}*/
public class ClientThread implements Runnable {
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
String date;
RemoteAccess access;
public RemoteAccess getAccess() {
return access;
}
public void setAccess(RemoteAccess access) {
this.access = access;
}
// Constructor
ClientThread(Socket socket) {
this.socket = socket;
System.out.println("Thread trying to create Object Input/Output Streams");
try
{
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
System.out.println("CT input Stream :"+sInput);
access = (RemoteAccess) sInput.readObject();
System.out.println(access.getFrom() +"Joined the chat room");
}
catch (IOException e)
{
e.printStackTrace();
System.out.println("Exception creating new Input/output Streams: " + e);
return;
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
date = new Date().toString() + "\n";
}
/*private void close() {
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {
e.printStackTrace();
}
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {
e.printStackTrace();
};
try {
if(socket != null) socket.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
*/
#Override
public void run()
{
System.out.println("List size is :"+Server.al.size());
for(int i=0;i<Server.al.size();i++)
{
try {
System.out.println("Socket input Stream :"+Server.al.get(i).socket.getInputStream());
System.out.println("Socket :"+socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
if(Server.al.get(i).access.getFrom()==access.getTo())
{
System.out.println("I am in if part :"+Server.al.get(i).access.getFrom() +"compare to :"+access.getTo());
PairHandler t = null;
try {
t = new PairHandler(access.getTo(),Server.al.get(i).socket,Server.al.get(i).socket.getInputStream(),Server.al.get(i).socket.getOutputStream(),socket.getOutputStream(),socket.getInputStream(),socket);
} catch (IOException e) {
e.printStackTrace();
}
Thread t1 = new Thread(t);
System.out.println("Connection initiated by in CT:"+access.getFrom());
t1.start();
}
else{
System.out.println("I am in else in CT");
}
}
}
}
PairHandler.java
This is where i am using two client socket
package customChat;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class PairHandler implements Runnable
{
long stbId;
Socket tvsocket;
ObjectInputStream tvsInput;
ObjectOutputStream tvsOutput;
Socket dtsocket;
ObjectInputStream dtsInput;
ObjectOutputStream dtsOutput;
PairHandler(long stbId,Socket tvsocket,Socket dtsocket)
{
this.stbId = stbId;
this.tvsocket = tvsocket;
this.dtsocket = dtsocket;
try
{
tvsOutput = new ObjectOutputStream(tvsocket.getOutputStream());
dtsOutput = new ObjectOutputStream(dtsocket.getOutputStream());
System.out.println("DT output Stream is :"+dtsOutput);
System.out.println("Tv outPut Stream is :"+tvsOutput);
System.out.println("RH input Stream :"+tvsocket.getInputStream());
tvsInput = new ObjectInputStream(tvsocket.getInputStream());
System.out.println("Tv input Stream is :"+tvsInput);
dtsInput = new ObjectInputStream(dtsocket.getInputStream());
System.out.println("DT input Stream is :"+dtsInput);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println("Exception creating in Pair Handler new Input/output Streams: " + e);
return;
}
}
public PairHandler(long to, Socket socket, InputStream inputStream, OutputStream outputStream,
OutputStream outputStream2, InputStream inputStream2, Socket socket2) {
stbId = to;
tvsocket = socket;
dtsocket = socket2;
try{
tvsOutput = new ObjectOutputStream(outputStream);
dtsOutput = new ObjectOutputStream(outputStream2);
System.out.println("DT output Stream is :"+dtsOutput);
System.out.println("Tv input Stream is :"+socket.getInputStream());
System.out.println("DT input Stream is :"+socket2.getInputStream());
tvsInput = new ObjectInputStream(socket2.getInputStream());
System.out.println("Tv input Stream is 2 :"+tvsInput);
dtsInput = new ObjectInputStream(socket2.getInputStream());
System.out.println("DT input Stream is :"+dtsInput);
System.out.println("Tv input Stream is :"+tvsInput);
// TODO Auto-generated constructor stub
}
catch (IOException e)
{
System.out.println("Exception in PH");
e.printStackTrace();
}
}
#Override
public void run()
{
try
{
//dtsInput = new ObjectInputStream(dtsocket.getInputStream());
System.out.println("DT socket :"+dtsInput);
if(dtsInput!=null){
RemoteAccess dtMsg = (RemoteAccess) dtsInput.readObject();
if(dtMsg !=null){
// write to tvscoket
System.out.println("I am here in Pair Handler");
sendTOTv(dtMsg);
}
}
// tvsInput = new ObjectInputStream(tvsocket.getInputStream());
System.out.println("TV socket :"+tvsInput);
if(tvsInput!=null){
RemoteAccess tvmsg = (RemoteAccess) tvsInput.readObject();
if(tvmsg !=null){
// write to dtsocket
sendToDT(tvmsg);
}
}
}
catch (IOException e)
{
e.printStackTrace();
System.out.println("Exception found while msg");
}
catch(ClassNotFoundException e2) {
e2.printStackTrace();
}
}
private void sendToDT(RemoteAccess tvmsg) {
// TODO Auto-generated method stub
// if Client is still connected send the message to it
if(!dtsocket.isConnected())
{
closeDtSocket();
}
try {
dtsOutput.writeObject(tvmsg);
}
catch(IOException e) {
System.out.println("Failed to deliver msg");
}
}
private void closeDtSocket() {
try {
if(dtsOutput != null) dtsOutput.close();
}
catch(Exception e) {
e.printStackTrace();
}
try {
if(dtsInput != null) dtsInput.close();
}
catch(Exception e) {
e.printStackTrace();
};
try {
if(dtsocket != null) dtsocket.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void closeTvSocket() {
try {
if(tvsOutput != null) tvsOutput.close();
}
catch(Exception e) {
e.printStackTrace();
}
try {
if(tvsInput != null) tvsInput.close();
}
catch(Exception e) {
e.printStackTrace();
};
try {
if(tvsocket != null) tvsocket.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void sendTOTv(RemoteAccess dtMsg) {
// TODO Auto-generated method stub
if(!tvsocket.isConnected())
{
closeTvSocket();
}
try {
tvsOutput.writeObject(dtMsg);
}
catch(IOException e) {
System.out.println("Failed to deliver msg");
}
}
}
RemoteAccess.java
package customChat;
import java.io.File;
import java.io.Serializable;
class RemoteAccess implements Serializable {
private static final long serialVersionUID = 1L;
private long to;
private long from;
private File file;
private String msg;
private int x ;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
RemoteAccess(){
}
RemoteAccess(long to,long from)
{
this.to=to;
this.from=from;
}
RemoteAccess(long to,long from,File file)
{
this.to=to;
this.from=from;
this.file=file;
}
RemoteAccess(long to,long from,int x,int y)
{
this.to=to;
this.from=from;
this.x=x;
this.y=y;
}
RemoteAccess(long to,long from,String msg)
{
this.to=to;
this.from=from;
this.msg=msg;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public long getTo() {
return to;
}
public void setTo(long to) {
this.to = to;
}
public long getFrom() {
return from;
}
public void setFrom(long from) {
this.from = from;
}
}
I supposed you want to customize client1 and client2. So you should create a class for each one :
public class Client1 extends Socket {
public Client1() {
super();
}
//Add stuff to customize
}
public class Client2 extends Socket {
public Client2() {
super();
}
//Add stuff to customize
}
Then create your class that contains your two sockets :
public class ClientDialog {
private Client1 client1;
private Client2 client2;
public ClientDialog() {
client1 = new Client1();
client2 = new Client1();
}
//Dialog between client
}

Why isn't my client socket inputstream receiving message sent from server socket outputstream

This is the SocketServer code that generates a server thread
public class ProcessorCorresponder {
protected final static Logger logger = LogManager.getLogger( ProcessorCorresponder.class );
private static int port = Integer.parseInt(PropertiesLoader.getProperty("appserver.port") == null ? "666" : PropertiesLoader.getProperty("appserver.port"));
private static int maxConnections = Integer.parseInt(PropertiesLoader.getProperty("appserver.maxconnections") == null ? "666" : PropertiesLoader.getProperty("appserver.maxconnections"));
public static void main(String[] args) {
logger.info("Starting server .. "
+ "[port->" + port
+ ",databaseName->" + databaseName + "]");
try (ServerSocket listener = new ServerSocket();) {
listener.setReuseAddress(true);
listener.bind(new InetSocketAddress(port));
Socket server;
int i = 0;
while((i++ < maxConnections) || (maxConnections == 0)) {
server = listener.accept();
logger.debug(
"New Thread listening on " + server.getLocalAddress().toString() + ":" + server.getLocalPort()
+ ", initiated from IP => " + server.getInetAddress().toString() + ":" + server.getPort()
);
MySocketServer socSrv = new MySocketServer (server);
Thread t = new Thread( socSrv );
t.start();
}
} catch (Exception ex) {
logger.error("Error in ProcessorInterface", ex);
}
}
}
Server code: This is a thread to handle one connection, there is a program that monitors a serversocket and spins off request threads as needed.
public class MySocketServer implements Runnable {
protected final static Logger logger = LogManager.getLogger(MySocketServer.class);
private final Socket server;
// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;
private StringBuffer buffHeartbeatMessage = new StringBuffer().append((char) 0).append((char) 0).append((char) 0)
.append((char) 0).append((char) 0).append((char) 0);
private Heartbeat heartbeat = new Heartbeat(/* 60 */3000, buffHeartbeatMessage.toString());
public MySocketServer(Socket server) {
this.server = server;
}
#Override
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(this.server.getInputStream()));
BufferedOutputStream out = new HeartbeatBufferedOutputStream(this.server.getOutputStream(),
heartbeat)) {
final StreamListener listener = new StreamListener(in);
listener.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getID() == ActionEvent.ACTION_PERFORMED) {
if (event.getActionCommand().equals(StreamListener.ERROR)) {
logger.error("Problem listening to stream.");
listener.setShouldContinue(false);
stopRunning();
} else {
String messageIn = event.getActionCommand();
if (messageIn == null) { // End of Stream;
stopRunning();
} else { // hey, we can do what we were meant for
logger.debug("Request received from client");
// doing stuff here
...
// done doing stuff
logger.debug("Sending Client Response");
try {
sendResponse(opResponse, out);
} catch (Exception ex) {
logger.error("Error sending response to OP.", ex);
}
}
}
}
}
});
listener.start();
while (shouldContinue) {
// loop here until shouldContinue = false;
// this should be set to false in the ActionListener above
}
heartbeat.setShouldStop(true);
return;
} catch (Exception ex) {
logger.error("Error in ESPSocketServer", ex);
return;
}
}
private void stopRunning() {
shouldContinue = false;
}
private void sendResponse(ClientResponse opResponse, BufferedOutputStream out) throws Exception {
logger.debug("Before write");
out.write(opResponse.getResponse().getBytes());
logger.debug("After write. Before flush");
out.flush();
logger.debug("After flush");
// this log message is in my logs, so I know the message was sent
}
}
My StreamListener class.
public class StreamListener extends Thread {
protected final static Logger logger = LogManager.getLogger(StreamListener.class);
public final static String ERROR = "ERROR";
private BufferedReader reader = null;
private List<ActionListener> actionListeners = new ArrayList<>();
private boolean shouldContinue = true;
public StreamListener(BufferedReader reader) {
this.reader = reader;
}
#Override
public void run() {
while (shouldContinue) {
String message;
try {
// client blocks here and never receives message
message = reader.readLine();
ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, message);
fireActionPerformed(event);
} catch (IOException e) {
e.printStackTrace();
ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ERROR);
fireActionPerformed(event);
}
}
}
public void setShouldContinue(boolean shouldContinue) {
this.shouldContinue = shouldContinue;
}
public boolean getShouldContinue() {
return shouldContinue;
}
public boolean addActionListener(ActionListener listener) {
return actionListeners.add(listener);
}
public boolean removeActionListener(ActionListener listener) {
return actionListeners.remove(listener);
}
private void fireActionPerformed(ActionEvent event) {
for (ActionListener listener : actionListeners) {
listener.actionPerformed(event);
}
}
}
My Heartbeat class
public class Heartbeat extends Thread {
private BufferedOutputStream bos = null;
private int beatDelayMS = 0;
private String message = null;
private boolean shouldStop = false;
public Heartbeat(int beatDelayMS, String message) {
this.beatDelayMS = beatDelayMS;
this.message = message;
setDaemon(true);
}
#Override
public void run() {
if (bos == null) { return; }
while(!shouldStop) {
try {
sleep(beatDelayMS);
try {
bos.write(message.getBytes());
bos.flush();
} catch (IOException ex) {
// fall thru
}
} catch (InterruptedException ex) {
if (shouldStop) {
return;
}
}
}
}
public void setBufferedOutputStream(BufferedOutputStream bos) {
this.bos = bos;
}
public BufferedOutputStream getBufferedOutputStream() {
return bos;
}
public void setShouldStop(boolean shouldStop) {
this.shouldStop = shouldStop;
}
public boolean getShouldStop() {
return shouldStop;
}
}
My HeartbeatBufferedOutputStream
public class HeartbeatBufferedOutputStream extends BufferedOutputStream {
private Heartbeat heartbeat = null;
public HeartbeatBufferedOutputStream(OutputStream out, Heartbeat heartbeat) {
super(out);
this.heartbeat = heartbeat;
this.heartbeat.setBufferedOutputStream(this);
heartbeat.start();
}
#Override
public synchronized void flush() throws IOException {
super.flush();
heartbeat.interrupt();
}
}
And finally here is the "Client" class
public class Mockup extends Thread {
protected final static Logger logger = LogManager.getLogger(Mockup.class);
// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;
public static void main(String[] args) {
new Mockup().start();
}
#Override
public void run() {
try (Socket socket = new Socket("localhost", 16100);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {
final StreamListener listener = new StreamListener(in);
listener.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getID() == ActionEvent.ACTION_PERFORMED) {
if (event.getActionCommand().equals(StreamListener.ERROR)) {
logger.error("Problem listening to stream.");
listener.setShouldContinue(false);
stopRunning();
} else {
String messageIn = event.getActionCommand();
if (messageIn == null) { // End of Stream;
stopRunning();
} else { // hey, we can do what we were meant for
// convert the messageIn to an OrderPower request, this parses the information
logger.info("Received message from server. [" + messageIn + "].");
}
}
}
}
});
listener.start();
StringBuffer buff = new StringBuffer("Some message to send to server");
logger.info("Sending message to server [" + buff.toString() + "]");
out.write(buff.toString().getBytes());
out.flush();
boolean started = false;
while (shouldContinue) {
if (!started) {
logger.debug("In loop");
started = true;
}
// loop here until shouldContinue = false;
// this should be set to false in the ActionListener above
}
logger.info("Exiting Mockup");
return;
} catch (Exception ex) {
logger.error("Error running MockupRunner", ex);
}
}
private void stopRunning() {
shouldContinue = false;
}
}
I have confirmed from logging messages that the Server sends a message to the BufferedOutputStream, and is flushed, but the Client logs indicate that it is blocked on the reader.readLine() and never gets the message.
You are reading lines but you are never writing lines. Add a line terminator to what you send.

Chat Application using socket not working over Internet in Java

I am currently developing chat application working over Internet.currently my application working fine over LAN but not working over Internet.I have also used port forwarding.I have done setting in modem and forward the port to private IP address but still it's not working.I got the error that "server isn't found".Please suggest me what I have to do and tell,Am I done the correct setting in modem or not??
Below is my server code...
Server.java
import java.util.*;
import java.net.*;
import java.io.*;
class Server implements ChatConstants
{
private static Vector list;
private ServerSocket ssocket ;
private Service service;
private static Socket socket;
private boolean done=false;
private static Hashtable userTable = new Hashtable();
private static Hashtable _userList = new Hashtable();
private static Hashtable _conflist = new Hashtable();
public Server() throws UnknownHostException
{
System.out.println("Initializing...");
list=new Vector(BACKLOG);
try {
ssocket= new ServerSocket(SERVER_PORT,BACKLOG);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Inside constructor"+e);
}
start();
}
public void start() throws UnknownHostException
{
byte[] data;
int header;
Socket _socket = null;
String hostname = null;
System.out.println("Server successfully started at "
+InetAddress.getLocalHost().toString()
+" port "+SERVER_PORT);
while(!done) {
try
{
_socket=ssocket.accept();
if(_socket != null) {
synchronized(list) {
list.addElement(_socket);
}
DataInputStream dis=new DataInputStream(_socket.getInputStream());
data = new byte[MAX_MESSAGE_SIZE];
dis.read(data);
Message message = ((Message)ChatUtils.bytesToObject(data));
System.out.println("Joined client "
+message._username+" at "+message._host+"...");
synchronized(userTable) {
userTable.put(message._username,_socket);
}
addUser(message);
sendUserList(message);
writeToClients(message);
service = new Service(_socket,hostname,message._user);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Thread exception"+e);
try {
_socket.close();
}
catch(Exception ex) {
ex.printStackTrace();
System.out.println("ERROR CLOSING SOCKET");
}
}
}//END WHILE
}
private void addUser(Message message)
{
synchronized(_userList) {
_userList.put(message._user.toString(),message._user);
}
}
public static void updateUser(User user)
{
User myuser;
synchronized(_userList) {
_userList.put(user.toString(),user);
}
}
public static synchronized void writeToClients(Message message)
{
byte[] data;
DataOutputStream dos;
for(int count=0;count<list.size();count++) {
try {
dos=new
DataOutputStream(((Socket)list.elementAt(count)).getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Output exception");
}
}//END FOR
}
public static void writeToClient(Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(userTable) {
try {
socket = (Socket)userTable.get(message._destination);
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("SEND EXCEPTION"+e);
}
}
}
public static void sendConferenceListToClient(Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(userTable) {
try {
Message mymessage= new Message(CONFERENCE_LIST);
Vector vector = (Vector)
_conflist.get(message._destination);
mymessage._username = message._username;
mymessage._destination = message._destination;
mymessage.userlist = vector;
socket = (Socket)userTable.get(message._username);
if(socket!=null) {
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(mymessage);
dos.write(data,0,data.length);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("CONFERENCE LIST EXCEPTION"+e);
}
}
}
public static void writeToPublicChat(Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(_conflist) {
try {
Vector svector = (Vector)_conflist.get(message._destination);
for(int cnt=0;cnt<svector.size();cnt++) {
synchronized(userTable) {
try {
socket = (Socket)userTable.get((svector.get(cnt).toString()));
if(socket!=null) {
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("PUBLIC CHAT EXCEPTION"+e);
}
}
}
} catch(Exception e){
e.printStackTrace();
System.out.println("PUBLIC EXCEPTION"+e);
}
}
}
public static void inviteToPublicChat(Vector svector,Message message)
{
Socket socket;
byte[] data;
DataOutputStream dos;
synchronized(_conflist) {
for(int cnt=0;cnt<svector.size();cnt++) {
synchronized(userTable) {
try {
socket = (Socket)userTable.get((svector.get(cnt).toString()));
if(socket != null) {
dos=new DataOutputStream(socket.getOutputStream());
data=ChatUtils.objectToBytes(message);
dos.write(data,0,data.length);
}
}
catch(Exception e) {
e.printStackTrace();
System.out.println("PUBLIC INVITE EXCEPTION"+e);
}
}
}
}
}
private void sendUserList(Message message)
{
int header=0;
String destination;
header=message._header;
destination = message._destination;
message._header = USERS_LIST;
message._destination = message._username;
message.userlist = new Vector(_userList.values());
writeToClient(message);
//Restore the headers
message._destination = destination;
message._header = header;
}
public static synchronized void removeUser(User user)
{
try {
Socket socket = (Socket)userTable.get(user.toString());
list.removeElement(socket);
_userList.remove(user.toString());
userTable.remove(user.toString());
}
catch(Exception e) {
e.printStackTrace();
System.out.println("ERROR REMOVING SOCKET "+e);
}
}
public static synchronized void processClientMessage(Message message)
{
switch(message._header) {
case CHANGE_STATUS:
updateUser(message._user);
writeToClients(message);
break;
case CLIENT_LOGOUT:
removeUser(message._user);
writeToClients(message);
break;
case CONFERENCE_CREATE:
Vector myvector = new Vector();
myvector.add(message._username);
_conflist.put(message._user.toString(),myvector);
case CONFERENCE_INVITE:
inviteToPublicChat(message.userlist,message);
break;
case CONFERENCE_JOIN:
Vector vector=null;
vector = (Vector)
_conflist.get(message._destination.toString());
vector.add(message._username);
_conflist.put(message._destination.toString(),vector);
writeToPublicChat(message);
break;
case CONFERENCE_DENY:
//_conflist.remove(message._user.toString(),message.userlist);
writeToPublicChat(message);
break;
case CONFERENCE_LEAVE:
Vector vectors =(Vector)
_conflist.get(message._destination.toString());
for(int count=0;count<vectors.size();count++) {
if(message._username.equals((vectors.elementAt(count).toString())))
vectors.remove(count);
}
if(vectors.size() != 0)
_conflist.put(message._user.toString(),vectors);
else//IF THERE ARE NO MORE USERS
_conflist.remove(message._user.toString());//DONE CONFERENCE
writeToPublicChat(message);
break;
case PUBLIC_CHAT:
writeToPublicChat(message);
break;
case CONFERENCE_LIST:
sendConferenceListToClient(message);
break;
default:
writeToClient(message);
}
}
public static void main(String args[]) throws Exception
{
Server chatserver=new Server();
}
}
//
// Service: Service class for each clients connected to server.
//
class Service implements Runnable, ChatConstants
{
private DataInputStream dis;
private Socket socket;
private boolean done=false;
private Thread thread;
private String hostname;
private User user;
public Service(Socket _socket,String _hostname,User user)
{
try {
this.socket = _socket;
this.hostname=_hostname;
this.user = user;
dis=new DataInputStream(socket.getInputStream());
thread=new Thread(this,"SERVICE");
thread.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("service constructor"+e);
}
}
public void run()
{
byte[] data;
while(!done)
{
try {
data = new byte[MAX_MESSAGE_SIZE];
dis.read(data);
Message message = ((Message)ChatUtils.bytesToObject(data));
Server.processClientMessage(message);
}
catch(Exception e) {
e.printStackTrace();
done = true;
Server.removeUser(user);
Message message = new Message(CLIENT_LOGOUT);
user.isOnline = OFFLINE;
message._user = user;
Server.writeToClients(message);
try {
socket.close();
} catch(Exception se) {
se.printStackTrace();
System.out.println("ERROR CLOSING SOCKET "+se);
}
//System.out.println("SERVICE THREAD EXCEPTION"+e);
}
}//END WHILE
}
}
Thanks in advance.
I think the
ssocket= new ServerSocket(SERVER_PORT,BACKLOG);
is making the issue. Use the version
ssocket= new ServerSocket(SERVER_PORT,BACKLOG,LOCAL_INET_ADDRESS);
and bind server to some constant local IP. Now use the port forwarding in the modem, to forward all requests to that local ip. Make sure that the firewall is not preventing you to use the port. Since firewall may allow a local networking but not to web.

Categories

Resources