An RMI Program is running on a remote machine(RMI Server), We invoked this program through the Web app(RMI client). When the RMI client invokes the RMI Server, the server instantiate a program and the result is send back to client through the simple network client code. The sample code as below.
RMI server code
try {
if(monitor == null) return;
monitor.stop();
SimpleClient sc=new SimpleClient(client,1131,"`file Monitor stopped");
//System.out.println("---aaaaa---");
sc.sendMsg();
System.out.println("Monitor stopped");
}catch(Exception ex){
ex.printStackTrace();
}
RMI Client code
public static List plusOne003Test(String ipAddress, boolean isstopped) {
ArrayList alist = null;
try {
System.out.println("All Plus one....plusOne003Test");
Class testClass = Class.forName("PlusOneClient11");
System.out.println("class Name::::::>"+testClass.getName());
Method testMethod = testClass.getMethod("plusOne003Test",
new Class[] { String.class,boolean.class});
alist = (ArrayList) testMethod.invoke(testClass.newInstance(),ipAddress,isstopped);
//System.out.println("ALIST::::::>"+alist);
System.out.println("before create server");
SimpleServer t=new SimpleServer(1131);
t.start();
Thread.sleep(10000);
System.out.println("after create server");
System.out.println("test3:::>" + alist.size());
} catch (Exception ex) {
ex.printStackTrace();
}
return alist;
}
network code for received the message from the RMI Server
public class SimpleServer extends Thread{
private ServerSocket serverSocket;
public SimpleServer(int port) throws IOException {
try{
ServerSocketFactory ssf=ServerSocketFactory.getDefault();
serverSocket=ssf.createServerSocket(port);
}catch(BindException be){
be.printStackTrace();
}
}
public void run(){
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
/*System.out.println("Just connected to "
+ server.getRemoteSocketAddress());*/
DataInputStream in =
new DataInputStream(server.getInputStream());
String rec=in.readUTF();
System.out.println("\n"+rec+"\n");
if(rec.contains("`")){
String rec1[]=rec.split("`");
**JOptionPane.showMessageDialog(null, rec1[0]+"\n"+rec1[1]);**
----------------------------------------------------------------
System.out.println("\n"+rec+"\n");
}
}catch(SocketTimeoutException s)
{
s.printStackTrace();
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
}
The code JOptionPane.showMessageDialog(null, rec1[0]+"\n"+rec1[1]); message needs to be displayed in the web app alert message.
You need to understand the difference between server side (JSP, Servlet) and client side (HTML, Javascript) code in this case. JSP is used to generate the HTML code, i.e. it runs on the server, generates the HTML that is sent to browser, and then stops. So it is not possible to put any messaging client's code into the JSP.
Basically, the web technology is a request-response technology, the communication is initiated by the client. But there are of course ways to implement also a server-initiated communication. I would recommend you to have a look at HTML5 WebSockets (e.g. http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html), which should be the most standard way to implement such functionality.
Related
I am trying to open a socket inside a bukkit plugin so i could send data to it using php or node but instead of socket remaining open after one use it just closes and also server does not load before this happens what should i do i am out of ideas.
Main:
public class Main extends JavaPlugin {
public void onEnable() {
saveDefaultConfig();
getConfig().options().copyDefaults(true);
System.out.println("[INFO] Main class loaded.");
start();
}
public void start() {
SocketServer server = new SocketServer();
try {
server.start(getConfig().getInt("port"), getConfig().getString("socket-password"));
System.out.println("[INFO] Main successfully called start.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Socket server class:
When called this should read information convert it into array check the first item in array and use it as auth code then array should be converted into string and used in Command executor class. This works fine but after one use this just closes
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port, String socketpwd) throws IOException {
System.out.println("[INFO] Socket server listening on: " + port);
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Boolean enabled = true;
try {
// Socket authentication
String message = in.readLine();
String suffix[] = message.split(" ");
System.out.println("Socket auth code used: "+ suffix[0]);
System.out.println("Socket pwd is: " + socketpwd);
if (socketpwd.equals(suffix[0])) {
out.println("Auth sucessfull!");
// do the following command from args here
String command = suffix[1];
int suffixL = suffix.length;
// add arguments to command
for (int i = 2; i < suffixL; i++) {
command = command + " " + suffix[i];
}
// call req exec
System.out.println("[INFO] Socket server contacted Request executor with: " + command);
RequestExecutor.executor(command);
enabled = false;
}
else {
out.println("Unrecognised auth code!");
}
} catch (NullPointerException e) {
System.out.println("Exception prevented!");
}
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}
Other problem as i mentioned is that bukkit server does not fully load before one request has been made to this socket.
Thank you for your help.
First of all you shouldn't be running a socket like that on the main thread, typically you should be running this on an async task using the Bukkit scheduler.
Then once you open the socket you should create a while loop to continuously poll for a connection and handle the incoming data. Instead what you are doing is opening the socket, reading a line and then dropping the connection.
You want to be doing something similar to
while(true){
Socket socket = serverSocket.accept();
}
See this webpage for some more info.
I have created a program that simply has a server which connects the port (6789) and a client when connects to this same port. However, my issue begins with having the server start and connect to port 6789.
The interesting thing is that my server works perfectly in Eclipse, however when it is embedded in HTML, it does not work although the GUI and other functionalities work. The following code is for starting up my server. I have not included the ClientThread or ServerGUI class since my main issue is getting the server to connect to the port anyways.
Is there another port I should be using instead of 6789 when on HTML?
Thank you!
public class Server {
private ServerGUI sg;
private int port;
// the boolean that will be turned of to stop the server
private boolean keepGoing;
HashSet<String> retailers;
HashSet<String> retailers_company;
ArrayList<HashSet<String>> al;
public Server(int port, ServerGUI sg) {
this.sg = sg;
this.port = port;
}
public void start() {
keepGoing = true;
try
{
ServerSocket serverSocket = new ServerSocket(port);
display("Server started on Port: " + port);
while(keepGoing)
{
Socket socket = serverSocket.accept();
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket);
t.start();
}
try {
serverSocket.close();
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
display("Exception on new ServerSocket: " + e + "\n");
}
}
}
For the server I have to alter the provided code into a multi-threaded server. For the client I have alter to it to make it read data from a text file.
So far I've managed to compile but when running on the client side it not only gives odd symbols but in the end it says "connection host lost". I've tried changing the socket number the same problem persists.
So this is what it looks like:
¼Ýsr♥Car´3▼3çw3û☻♦DmileageLmodelt↕Ljava/lang/String;Lownerq~☺L
registrationq~☺xp#
"Honda Civic""John S"q~sq~##t-sq~#Òêt
"Vokswagen"t "Maria B"q~
Connection to host lost.
This is my code for server:
//a simple client/server application: car registration
//a SERVER program that uses a stream socket connection to exchange objects
import java.net.*;
import java.io.*;
public class CarsServer {
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;; // TCP socket used for listening
try {
/* step 1: create a server socket port number: 8000 */
serverSocket = new ServerSocket(5200);
int i = 0;
for(;;){
/* setp 2: listen for a connection and create a socket */
System.out.println("*** this server is going to register the cars ***");
System.out.println("listening for a connection...");
Socket clientSocket = serverSocket.accept();
System.out.println("Spawning " + i++);
new CarsClient(clientSocket, i).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
/* step 5: close the connection to the client */
System.out.println("*** the server is going to stop running ***");
serverSocket.close();
}
}
}
And for Client
//a simple client/server application that exchanges OBJECTS
//a CLIENT program that uses a stream socket connection to exchange objects
import java.net.*;
import java.io.*;
class CarsClient extends Thread{
private Socket incoming;
private int client;
public CarsClient(Socket i, int c){
this.client = c;
this.incoming = i;
}
public void run(){
try {
/*
* step 2: connect input and output streams to the socket
*/
BufferedReader oisFromServer = new BufferedReader(new FileReader("Cars.txt"));
ObjectOutputStream oosToServer = new ObjectOutputStream(incoming.getOutputStream());
System.out.println("I/O streams connected to the socket");
/*
* step 3: communicate with the server
*/
Car[] cars = new Car[3];
int n = 0;
String[] l;
String line;
while((line = oisFromServer.readLine()) != null){
l = line.split(", ");
try {
// receive an object from the server
cars[n] = new Car(l[0], l[1], Integer.parseInt(l[2])); // casting!
// send an object to the server
oosToServer.writeObject(cars[n]);
//oosToServer.flush();
System.out.println("\n### send this car to the server for registration:\n" + cars[n]);
System.out.println("\t###### the car returned by the server:\n"+ cars[n]);
n++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
} catch (EOFException eof) {
System.out.println("The server has terminated connection!");
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* step 4: close the connection to the server
*/
System.out.println("\nClient: closing the connection...");
oosToServer.close();
oisFromServer.close();
incoming.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("the client is going to stop runing...");
} // end run
}
I'm new to programming so please help me out.
It appears that your issue is here:
while((line = oisFromServer.readLine()) != null){
You are consuming all the lines of text, and once that's done, oisFromServer is going to return null.
To solve this, I recommend you use the raw InputStream and InputStream.read() from the socket. Also, once upon a time I wrote a utility class for this kind of blocking reading. See DataFetcher, and its dependencies in the same project package
I'm working on a project which expects a TCP client and Server, where server echoes the message back to client. Following is from the assignment:
The server application shall:
Listen for TCP connections on a well known IP address and port
Accept connections initiated on that port
Receive messages from the client and echo them back
Continue to do this until the client drops the connection.
The client application shall:
Establish a connection with the server at its well known IP address and port
Send messages in an asynchronous manner to the server. The format of the message is
of your choice; however, it must contain enough information in order for it to be
recognized on its return from the server.
I have completed the coding for Server, and this is what i've come up with for the client.
My questions:
What does it mean that Server listens for TCP connections on a well known IP and Port In my implementation, i've used ServerSocket which accepts the port server listens on. Did i interpret it correctly?
In my current implementation of TCPClient, client sends messages to Server, but the println() seems to be a blocking call, which makes it Synchronous. What can i do to make my client asynchronous?
For brevity, I havent added the code of TCPServer, let me know if it is needed
UPDATE**
Based on the feedback, i have modified by TCPClient class. After receiving client request, i spawn two threads ReceiveMessage and SendMessage. Doing that gives me following exception:
[Client] Message sent: Message from Client 97
[Client] Message sent: Message from Client 98
[Client] Message sent: Message from Client 99
[Client] Done Sending all the messages
java.net.SocketException: Socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at org.chanders.client.ReceiveMessage.run(ReceiveMessage.java:18)
at java.lang.Thread.run(Thread.java:680)
Following is the new Client Code:
public class TCPClient {
Socket clientSocket = null;
OutputStream out = null;
BufferedReader in = null;
String message = "Hello from Client";
int messagecount = 100;
// server credentials
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 50001;
protected void execute() {
try {
clientSocket = new Socket(SERVER_ADDRESS, SERVER_PORT);
Thread send = new Thread(new SendMessage(clientSocket.getOutputStream()));
Thread receive = new Thread(new ReceiveMessage(clientSocket.getInputStream()));
send.start();
receive.start();
//For server to wait until send and receive threads finish
send.join();
receive.join();
} catch (UnknownHostException uhe) {
System.err.println("Couldnt find host: " + SERVER_ADDRESS);
uhe.printStackTrace();
System.exit(-1);
}catch(IOException ioe) {
System.err.println("Couldnt get I/O: " + SERVER_ADDRESS);
ioe.printStackTrace();
System.exit(-1);
}catch(InterruptedException ie) {
System.err.println("Thread.join failed: ");
ie.printStackTrace();
System.exit(-1);
}
finally {
//cleanup();
}
}
private void cleanup() {
try {
clientSocket.close();
}catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
TCPClient client = new TCPClient();
client.execute();
}
public class SendMessage implements Runnable {
OutputStream out = null;
String message = "Message from Client";
int messageCount = 100;
public SendMessage(OutputStream out) {
this.out = out;
}
public void run() {
PrintWriter writer = new PrintWriter(out);
try {
for (int i = 0; i < messageCount; i++) {
String m = message + " " + i;
writer.println(m);
System.out.println("[Client] Message sent: " + m);
}
System.out.println("[Client] Done Sending all the messages");
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
} finally {
cleanup();
}
}
private void cleanup() {
try {
out.close();
}catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
public class ReceiveMessage implements Runnable {
InputStream in = null;
String message;
public ReceiveMessage(InputStream in) {
this.in = in;
}
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
while ((message = reader.readLine()) != null) {
System.out.println("[Client] Received message from Server: "
+ message);
}
System.out.println("[Client] Done Receiving messages from Server");
} catch (Exception e) {
e.printStackTrace();
} finally {
cleanup();
}
}
private void cleanup() {
try {
in.close();
}catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
In this context, Asynchronous probably doesn't mean that you can't use println, but that the client must be able to recevie messages while it's sending new ones.
The client should create the socket and then create two threads, one to send messages and the other to recive and print them.
Update
To avoid the exception, use clientSocket.shutdownOutput() instead of closing the output stream.
You could move the send code back to the main thread and keep a separate thread for the receive code or call shutdownOutput() after joining the send thread. Whatever works better for you.
Use a separate thread for each client. When you write something, in the server end , there must be a method which accepts the string. Otherwise it will be blocking. Paste your server code.
Well known ports are port numbers that have been specifically designated for particular protocols, for example 80 is for HTTP and 443 is for HTTPS. Are you meant to be implementing a particular protocol? If you are I would suggest you use the port number for that protocol. Wikipedia has a list of well known port numbers here:
http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
If this is a professional assignment (as opposed to a some homework) then I would strongly recommend the Netty Server, which is basically a NIO client server framework. It significantly simplifies/streamlines the development of this sort.
Make sure to check their documentation as it provides examples implementing exactly the server/client functionality stated in the question.
If this is a homework then this example should provide all necessary details. Please also check Oracle resources.
ok is hard for me to describe my problem now but then i will try my best to in order for me to get some assist.
technically i have a server.java and client.java as a super class. and my layout structure for my server and client connection goes like this
MAIN SERVER --- CLIENT/SERVER ----- CLIENT
my main problem is the this CLIENT/SERVER part is 1 driver class that calls 2 different classes which is CLIENT and SERVER together... and this creates a problem when my CLIENT sends something that needs to be received by MAIN SERVER side needs to go through CLIENT/SERVER part. if is that condition happens..
the CLIENT of course need to interact with CLIENT/SERVER (SERVER) part because is a SERVER that accepts the CLIENT data. but now i wanted the (SERVER) part in the CLIENT/SERVER to transfer the data to (CLIENT) in the CLIENT/SERVER part so that it can be send to the MAIN SERVER
how is it possible for me to write something that allows the CLIENT/SERVER to interact with each other so it can transfer the data between them vise versa? how ever this is my code for calling the CLIENT and SERVER together
public class Slave {
public static void main(String args []) throws IOException{
try{
// set Config file settings to slave mode
Config cfg = new Config("Slave");
String MasterServerIP = cfg.getProperty("ServerIP");
String MasterServerPort = cfg.getProperty("ServerPort");
String SlaveServerPort = cfg.getProperty("ListeningPort");
System.out.println("Slave Client connecting to Master Server");
// start connect to master server by calling the SlaveClient class
new SlaveClient(MasterServerIP,Integer.parseInt(MasterServerPort)).start();
int numClient = 0;
ServerSocket listener = new ServerSocket(Integer.parseInt(SlaveServerPort));
System.out.println("Server starts running");
try{
while(true){
// start listening to the server port by calling SlaveServer class
new SlaveServer(listener.accept(), numClient++, Integer.parseInt(SlaveServerPort)).start();
}
} finally {
listener.close();
}
} catch (FileNotFoundException file) {
System.out.println("File Not Found Error: "+file.getMessage());
}
}
}
the above is only the driver class that calls the 2 object class which is the SERVER and CLIENT side.
i will attach my slaveserver and slaveclient code here but i am not sure how to do it like you said
public class SlaveServer extends Server {
private JFrame frame = new JFrame();
private JTextArea msgArea = new JTextArea();
private JTextArea connectionArea = new JTextArea();
// SlaveServer Constructor
public SlaveServer(Socket socket, int numClient, int port) {
super(socket, numClient, port);
}
public void writeToMsg(String msg){
msgArea.append(msg+"\n");
}
public void writeToConnection(String msg){
connectionArea.append(msg+"\n");
}
public void run(){
try{
startGUI();
// initial BufferedReader and PrintWriter object by binding it with Socket
BufferedReader in = new BufferedReader(new InputStreamReader(getSocket().getInputStream()));
PrintWriter out = new PrintWriter(getSocket().getOutputStream(), true);
// welcome message send from server to client
out.println("Welcome to the Slave Server port:"+getPort()+" client #"+getNumClient());
while(true){
String readmsg = in.readLine();
writeToMsg(readmsg);
}
} catch (IOException e){
writeToMsg("Error in closing Socket");
}
writeToConnection("Connection from client #"+getNumClient()+" is closed");
}
}
public class SlaveClient extends Client{
private BufferedReader in;
private PrintWriter out;
private JFrame frame = new JFrame();
private JTextArea msgArea = new JTextArea();
private JTextArea connectionArea = new JTextArea();
// SlaveClient Constructor
public SlaveClient(String ip, int port) {
super(ip, port);
}
public void run(){
startGUI();
Socket sock = null;
try {
sock = new Socket(getIp(), getPort());
} catch (IOException e) {
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
try {
out = new PrintWriter(sock.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
out.println("TEST");
// while loop for reading message from server
while(true){
try {
getMsg(in);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
So you are trying to write a proxy?
You you need to give the server half of the proxy a reference to the client half, so that it can forward the data.
Then create a method in the client half to accept messages from the server half.
So each message you read in at the server half, you pass to the client half. The client half can then pass it to the real server.