JAVA run multiple linked classes - java

I need to run different linked classes in java.
• The main one : Robot.java
• The second one : Request.java
I simulate a remote (with a TCP server) which controls Request which is a TCP client.
When Request received an information from the TCP server, it is stocked in String req.
I need to access req from Robot to decode and execute the request.
Thus in the Robot's constructor I do :
Request r = new Request("My robot");
r.setServer()
setServer() contains :
try{
socket = new Socket(IP, PORT);
System.out.println(socket);
out = new PrintWriter(socket.getOutputStream(), true);
out.println("NewRobot:"+getRobotName()); //Send the information that I'm creating a new robot !
String message ;
do {
in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()
)
);//get response from server
message = in.readLine() ;
System.out.println(message);
setReq(message); // Message always contains the request, so I set the request var
}while(!message.matches("^.*STOP.*$"));
in.close();
out.close();
socket.close();
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
The problem is when I do r.setServer() Robot.java runs while(!message.matches("^.*STOP.*$");
So the rest of the program is executed only when Request receive STOPwhile I need to access to each received request.
To access to this request I thought I could use a Timer in Robot, so each 100ms it calls r.getReq() to execute it.
What could I do to execute both classes with letting them linked as they are ?
Thanks, Lucas ^

Related

Java client receiving message from NodeJS server via socket

So basically I'm trying to communicate between a Java client and a NodeJS server. Java sends a message via a socket, Node receives it using an event listener, then Node tries to send a response to Java. Something like "OK" because the message was received.
Java (in Main.java)
try {
Socket s = new Socket("localhost", 6666);
// Send a message to the server
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8);
out.write("test");
out.flush();
// Receive a message from the server
InputStream input = s.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
System.out.println(line);
} catch (Exception e) {
System.out.println(e);
}
NodeJS
var net = require('net');
var server = net.createServer(function (connection) {
console.log("Client connected");
connection.on('data', function (data) {
console.log('Request from', connection.remoteAddress, 'port', connection.remotePort);
console.log(data.toString())
connection.write("OK");
});
})
server.listen(6666, () => console.log(`Server is listening...`));
The server displays:
Server is listening...
Client connected
Request from ::ffff:127.0.0.1 port 65025
test
but the client is empty, it doesn't get server's response.
I can't figue out where the problem is. I found countless examples for two-way socket communications, but most of them between a client/server written both for Java/NodeJS. Their code was still similar with what I wrote, but doesn't work. Thanks a lot!

Socket client not receiving messages from server only when server performs a loop

I am trying to make a server (written in Python) and a client (written in Java) to communicate. The server code is the following:
import socket # Import socket module
connection=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.bind(('',12800))
connection.listen(5)
connection_with_client, info_connection = connection.accept()
msg=b""
while(msg!=b"stop"):
print("Entering loop")
msg = connection_with_client.recv(1024)
connection_with_client.send(b"This is a message")
print("Sent")
connection_with_client.close()
connection.close()
The client code is:
try {
socket = new Socket(InetAddress.getLocalHost(),12800);
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print("stop");
out.flush();
System.out.println("Sent");
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String message_from_server = in.readLine();
System.out.println("Received message : " + message_from_server);
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The strange thing is: when the client sends the message "stop", everything goes fine, message from server is received by the client. Now, when the client sends another message than "stop", the server tells it has sent the message, and enters the loop a second time, however the client never receives the message and gets stuck at the in.readLine() instruction.
I really don't get why as the first passage in the loop should have the same effects in both situations... Any help welcome!
On client side you are using readLine. Obviously, this reads the line, but how it detects where the line ends? The answer is:
you server should append line ending to all messages you send to client.
Try append b'\r\n' or whatever are lineendings on your OS. As far as readLine is called on client side, you should append line ending of a client, not server OS.
For Windows it is b'\r\n'
For Linux b'\n'

Android socket wait issue

Hello I have an app that connect to a remote server using sockets
socket = new Socket();
socket.connect(new InetSocketAddress(Ip, portNum), 7000);
I have 2 methods send & receive
the scenario in send is
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
in method receive
String msg = "";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (in.ready()) {
msg = msg + (char) in.read();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
in AsyncTask of a different class I call
send();
String response=receive();
The above code is not sending or receiving without a wait period
i.e
Thread.sleep(2000);
I know sleep is a bad approach
what is the best scenario should I use?
Is it better to make an AsyncTask within send method and another one for receive method.
Here is where I use sleep and what data send & receive
client.send(some sql statement representED as json format);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// sql select result represented as json
String RESULT = client.recive();
Likely your server is not listening before you try to connect. Though this is unclear from the code you have posted. You'll need to show both server and client code there.

Chat: Sending message to all clients on a server

I have a server-client application set. (HOMEWORK)
So far I have figured out how to have multiple clients connect to the server and have the server aggregate the messages the clients send, as well as having the server send the client's message back to the client and displaying it in the chat pane.
My issue is trying to send a message to multiple clients. I am only allowed to use ServerSocket and Socket libraries.
Say I have 2 clients connected to the server. One client sends a message, the message is displayed in the client's chat. The second client sends a message, the first client does NOT receive it, and the second client's chat window displays the first client's message.
Essentially the server is sending the most recent message that the respective client has not displayed in the chatbox, and I have no idea why or how.
Code for server-to-client communication :
Class CommunicationThread extends Thread {
//Vector containing all client sockets currently connected
//Held offsite, here for clarity
public Vector<Socket> socketVector;
public CommunicationThread (Socket clientSoc, Server ec3, Vector<Socket>socketVectorg)
{
//add new socket to vector, start thread
clientSocket = clientSoc;
socketVectorg.add(clientSocket);
this.socketVector = socketVectorg;
gui = ec3;
}
public void run()
{
System.out.println ("New Communication Thread Started");
try {
//Client's chat box (output)
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
//Input line from client
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Server: " + inputLine);
gui.history.insert(inputLine + "\n", 0);
//*************HERE IS MY ISSUE*******************
for(Socket s : socketVector){
out = new PrintWriter(s.getOutputStream(),
true);
out.println(inputLine);
}
if (inputLine.equals("Bye."))
break;
if (inputLine.equals("End Server."))
gui.serverContinue = false;
}
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
//System.exit(1);
}
}
}
I know I am overwriting "out" but I don't think that is my issue so it is in my code while I am testing.
My issue is marked in the code above. The vector accurately stores the socket ID, and since I am creating a new PrinterWriter based on the vector, I would only assume that it would get the output field of the respective client, but it does not.
My intuition is that it is a problem with threading or closing the output, but I honestly don't know.
Any recommendations are appreciated.
Your problem it seems to me is that you want to do the input and output work on the client socket all in the same place, and there's no need for that. The client socket's output stream can be written to in the GUI thread, and all in one place. You can keep a collection of the output streams if need be and when you want to reply to all, iterate through the collection (probably a HashMap<String, OutpuStream> where the String is some client identifier) and send the messages.

Growl forwarding to Java server

I have a java server which is using TCP and sockets to connect to an Android application (the client) and sends strings (currently taken in from a scanner object) which are then displayed as notifications by the client.
heres the Server code without all the imports.
public class Server {
// define our Main method
public static void main(String[] args) throws IOException {
// set up our Server Socket, set to null for the moment.
ServerSocket serverSocket = null;
boolean isConnected = false;
// Lets try and instantiate our server and define a port number .
try {
serverSocket = new ServerSocket(6789);
isConnected = true;
System.out.println("*** I am the Server ***\n");
// make sure to always catch any exceptions that may occur.
} catch (IOException e) {
// always print error to "System.err"
System.err.println("Could not listen on port: 6789.");
System.exit(1);
}
// We always want to check for connection from Clients, so lets define
// a for ever loop.
for (;;) {
// define a local client socket
Socket clientSocket = null;
// lets see if there are any connections and if so, accept it.
try {
clientSocket = serverSocket.accept();
// don't forget to catch your exceptions
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
// Prepare the input & output streams via the client socket.
// fancy way of saying we want to be able to read and write data to
// the client socket that is connected.
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(clientSocket.getOutputStream(),
true);
while (isConnected) {
// read a sentence from client
String hiFromClient = inFromClient.readLine();
// Set up the logging system and timestamp and log message.
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter=
new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
try{
// Create file
File fstream = new File("log.txt");
FileWriter out = new FileWriter(fstream);
out.write(hiFromClient + " " + dateNow);
//Close the output stream
out.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
// Print the client sentence to the screen
System.out.println("The Client said: "+hiFromClient);
// Reply to the client
Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();
outToClient.println(sentence );
System.out.println("The Server said: " + sentence);
}
// always remember to close all connections.
inFromClient.close(); // the reader
outToClient.close(); // the writer
clientSocket.close(); // and the client socket
}
}}
Growl uses port 23053 for notification forwarding. What i am hoping to do is to listen in on 23053 and send anything in from that as a string to the client connected at 6789. Sadly Growl binds the port number so a new Socket connection cant be made.
Any one have any ideas on how i could get notifications from the port number growl uses or even just use growl as the server for the client itself (the client's code is very similar to the servers by the way just using Socket instead of ServerSocket)
Any help on this would be greatly appreciated, its wrecking my brain
All the best,
Patrick.
There is a round-about way you could do it. If you are desperate, read on:
Growl can forward any notifications it receives to another machine running Growl (configured on the Network tab). Growl uses the GNTP protocol (a TCP-based protocol: http://www.growlforwindows.com/gfw/help/gntp.aspx) to forward the messages. The trick is that that 'other machine running Growl' doesnt have to really be another machine OR running Growl per se, it just needs to appear to Growl that it is. Growl (on the Mac, which is what I assume you are using) will automatically detect any other machines on the network running Growl (using Bonjour and looking for the _gntp._tcp service name), so if your server advertises itself as supporting the GNTP protocol, Growl should show it in the list of available destinations. (Growl for Windows also lets you manually add a hostname/port to forward to, but I dont believe the Mac version currently allows that).
So then you could configure Growl to forward notifications to your server using its already-built-in capabilities. You would have to implement code in your server to receive the GNTP packets (the format is very similar to HTTP headers) and parse them. Then you could forward the notifications using your current server code.
Still with me? I did say it was round-about, but it is not only technically possible, but I have built a Growl-impersonating daemon before so that I could have notifications forwarded from Growl to my custom code. Not suggesting it as the best idea, but just an alternative since you asked.

Categories