I have Developed an Stand alone application (.jar) which is working on Linux environment, I want to Keep this Application on a server(Linux) and want to access through other systems.
Please suggest if this is Possible.
Have you considered Java Webstart ? It'll allow clients to download your application from a webserver and run it locally.
It's traditionally used with GUI (Swing etc.) apps, but I've used it to run daemon and server processes locally.
It'll handle application updates automatically so your clients will only download a version if they'll need it. Otherwise they'll access their locally cached version.
Linux system implements the Berkeley socket API, so yes, you can open communication for the other machines.
For this, you can use package java.net. For socket connection we can use: Socket, ServerSocket, and SocketAddress.
Socket is used for the client, ServerSocket is used to created a socket server, and SocketAddress is used to provide information that will be used as a target socket.
As the illustration, please find the projects below:
First Project SocketServerApp.java - build this and then run java -jar SocketServerApp.jar
package socketserverapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerApp {
public static void main(String[] args) throws IOException {
//we defines all the variables we need
ServerSocket server = null;
Socket client = null;
byte[] receivedBuff = new byte[64];
int receivedMsgSize;
try
{
//activate port 8881 as our socket server
server = new ServerSocket(8881);
System.out.println("Server started");
//receiving connection from client
client = server.accept();
System.out.println("Client connected");
}
catch (IOException e)
{
System.out.println(e.getMessage());
System.exit(-1);
}
//prepare data stream
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
//greet user if there is a client connection
String data;
data = "Hello from the Server!";
out.write(data.getBytes());
//accepting data from client and display it in the console.
java.util.Arrays.fill(receivedBuff, (byte)0);
while (true) {
receivedMsgSize = in.read(receivedBuff);
data = new String(receivedBuff);
//if client type "exit", then exit loop and close everything
if (data.trim().equals("exit"))
{
out.write(data.getBytes());
break;
}
java.util.Arrays.fill(receivedBuff, (byte)0);
System.out.println ("Client: " + data);
}
//close all resources before exiting
out.close();
in.close();
client.close();
server.close();
}
}
Second project is the SocketClientApp.java - build this and then run java -jar SocketClientApp.jar
package socketclientapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClientApp {
public static void main(String[] args) throws IOException {
Socket client = null;
InputStream in = null;
OutputStream out = null;
byte[] receivedMsg = new byte[64];
try {
client = new Socket("localhost", 8881);
in = client.getInputStream();
out = client.getOutputStream();
} catch (UnknownHostException e) {
System.err.println(e.getMessage());
System.exit(1);
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}
String fromServer;
String fromUser;
in.read(receivedMsg);
fromServer = new String(receivedMsg);
System.out.println("Server: " + fromServer);
fromUser = "Hello from Client";
System.out.println("Sent to server: " + fromUser);
out.write(fromUser.getBytes());
fromUser = "exit";
out.write(fromUser.getBytes());
System.out.println("Sent to server: " + fromUser);
out.close();
in.close();
client.close();
}
}
Short to say this is a TCP/IP Communication. This type of communication method is very usual in an enterprise that has many kinds of softwares.
Hope that helps.
Related
I created restful API(with maven) which connect to MySQL. I want to connect with the Java socket server I created earlier. But I couldn't figure out how to do this. I tried to connect with HttpURLConnection over Server.java but it didn't connect yet. Is it a good way to connect? Or should i try different way for this? And also I created new maven project and putted Server.Java and Client.Java in it. But it is a just attempt. I am not sure is it necessary or not.
Server.JAVA
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Server {
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
// System.out.println("Client accepted");
// HttpURLConnection attempt
URL url = new URL("http://localhost:8080/update/3");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("PUT");
http.setRequestProperty("Content-Type", "application/json");
http.setDoOutput(true);
OutputStream stream = http.getOutputStream();
String data = "{\n \"firstName\":\"Can\",\n \"lastName\":\"Doe\",\n \"occupation\":\"xxx\"\n}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
stream.write(out);
System.out.println(http.getResponseCode() + http.getResponseMessage());
http.disconnect();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Stop" is sent
while (!line.equals("Stop"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server( 5000);
}
}
I tried to connect two machines using Socket.
I put client code in Machine A:
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try {
Socket s = new Socket("IP ADDRESS",5555);
// Socket s = new Socket("localhost",6669);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
Run the server code in Machine B
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(5555);
Socket s = ss.accept(); //establishes connection
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = (String) dis.readUTF();
System.out.println("message= " + str);
ss.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
Both in machine in same network
But its not running and no error also coming in CMD.
First of all, when I compile the code using "localhost" as the hostname, and run the client and server apps on the same machine ... it works. The server receives the message and prints it.
From this, I conclude that the code is correct (enough) and the real problem is something to do with your networking; e.g.
It might be a routing problem.
It might be a firewall problem.
There might be something wrong with your physical network or network interfaces.
However none of these are programming problems.
I am new to java and network programming for the most part. I want to write a program that automatically backs up my texts to my computer whenever my phone connects to my home wifi.
I am working on creating java classes that will handle sending data over the network. Using some questions found here, I came up with this implementation but I have some questions regarding some of the methods used in what I learned from.
Two Questions Regarding this code
I totally used a question from SO for the send methods in my client. The sendText uses a new thread, but the sendFile doesn't. Any particular reason why?
2. At which point in the code does the server actually know when there has been a message sent to the port? Is it at the method accept() call or is it when the BufferStream readLine() is checked? Does accept just grab data and throw it into the buffer? null implying the data grabbed was not a signal sent from a client?
Does the accept() method block execution of the code until a connection attempt is made from a client?
Thanks!
KServ
//Used to launch the server
public class KServ {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java KServ <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
KServer server = new KServer(port);
while (true) { //added this to keep the server polling for new data
server.run();
}
}
}
KServer
//Server class. Should handle data incoming
import java.net.*;
import java.io.*;
public class KServer {
private int port;
public KServer(int PORT) {
port = PORT;
}
public void run() {
try (
ServerSocket sSocket = new ServerSocket(port);
Socket cSocket = sSocket.accept();
PrintWriter out = new PrintWriter(cSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
) {
String input;
while ((input = in.readLine()) != null) {
System.out.println(input);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port " + port + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
Client
//launches KClient object and uses it to send input from console to the server
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java Client <ip number> <port number>");
System.exit(1);
}
String ip = args[0];
int port = Integer.parseInt(args[1]);
KClient client = new KClient(ip,port);
String msg;
Scanner inStream = new Scanner(System.in);
while((msg = inStream.nextLine()).length() > 0) {
client.sendText(msg);
}
}
}
KClient
//Will be used to establish connection with server and send data from phone
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class KClient {
private String server;
private int port;
public KClient(String Server,int Port) {
server = Server;
port = Port;
}
public void sendFile(String fileName) {
File file = new File(fileName);
FileInputStream fileInputStream;
BufferedInputStream bufferedInputStream;
OutputStream outputStream;
try {
client = new Socket(server,port);
byte[] bytes = new byte[(int) file.length()];
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedInputStream.read(bytes, 0, bytes.length);
outputStream = client.getOutputStream();
outputStream.write(bytes,0,bytes.length);
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Socket client;
private OutputStreamWriter outputStreamWriter;
public void sendText(String msg) {
System.out.println("Send Message!");
new Thread(new Runnable() {
#Override
public void run() {
try {
client = new Socket(server,port);
outputStreamWriter = new OutputStreamWriter(client.getOutputStream(), "ISO-8859-1");
outputStreamWriter.write(msg);
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
BufferedReader inStream;
public boolean Shake() {
try {
client = new Socket(server,port);
inStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
I totally used a question from SO for the send methods in my client. The sendText uses a new thread, but the sendFile doesn't. Any particular reason why?
Unanswerable. Ask the author. Both sends can block. As the file is presumably longer than the text, it would have made more sense to do it the other way round.
2. At which point in the code does the server actually know when there has been a message sent to the port? Is it at the method accept() call
No.
or is it when the BufferStream readLine() is checked?
Yes.
Does accept just grab data and throw it into the buffer?
No. It grabs a connection and returns it as a socket. Nothing to do with data whatsoever.
null implying the data grabbed was not a signal sent from a client?
You seem to be actually asking about BufferedReader.readLine() here, not ServerSocket.accept(), which doesn't return null. readLine() returns null when there is no pending data to be read and the peer has closed the connection.
Does the accept() method block execution of the code until a connection attempt is made from a client?
More or less. It blocks until there is a complete connection waiting to be accepted, which isn't quite the same thing, as there is a queue.
I will add that you have copied, or written, some truly terrible code here. There are much better examples.
I don't know this is possible or not.First I wrote client and server in Node.js and then both server and client wrote in Java those were worked as expected. Now I'm interested in connect Java server and Node.js client. But problem is cant send date between them
This is server side code which is written in Java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
public MyServer() {
}
public static void main(String args[]){
ServerSocket serverSocket= null;
Socket socket =null;
DataInputStream datainputstream=null;
DataOutputStream dataoutputstream=null;
try{
serverSocket = new ServerSocket(8888);
System.out.println("Listening ...");
}catch(IOException e){
e.printStackTrace();
}
while(true){
try{
socket = serverSocket.accept();
datainputstream = new DataInputStream(socket.getInputStream());
dataoutputstream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip:"+socket.getInetAddress());
System.out.println("message:"+datainputstream.readUTF());
dataoutputstream.writeUTF("HELLO !");
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket!=null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(datainputstream!=null){
try{
datainputstream.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(dataoutputstream !=null){
try{
dataoutputstream.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
}
This is client side code which is written in Node.js
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 8888;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('connected to: ' + HOST + ':' + PORT);
client.write('Data comming from client...');
});
client.on('data', function(data) {
console.log(data.toString());
//client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
Your server (Java) is expecting a message from the client before it sends anything. It will block until it receives such a message. Since the server seems to not receive this message, either the client is not actually sending its message (ie, it's queueing it until it receives more data to send), or the server is expecting to receive more data.
The documentation for DataInputStream.readUTF() claims that it expects length-prefixed strings. That's not what your client is writing. The server is probably interpreting the first two bytes of your string as a length, then trying to read that many bytes of data, Since there isn't that much data available, it's going to wait for more from the client. Try using BufferedReader.readLine() instead, and make sure that your client is sending a newline at the end of its output.
If that doesn't work, try finding a way to flush the socket on the client side. I don't know Node.js, but a quick skim of the documentation suggests that socket.end() might help, although that won't work if you need to send more data later on.
Here is the solution for this
Server side code
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedInputStream;
import java.io.*;
public class MyServer {
public MyServer() {
}
public static void main(String args[]){
ServerSocket serverSocket= null;
Socket socket =null;
BufferedReader datainputstream=null;
try{
serverSocket = new ServerSocket(8888);
System.out.println("Listening ...");
}catch(IOException e){
e.printStackTrace();
}
try{
socket = serverSocket.accept();
}catch(IOException e){
System.out.println("can't listen given port \n");
System.exit(-1);
}
try{
datainputstream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("ip:"+socket.getInetAddress());
}catch(IOException e){
System.out.println("can't read File \n");
System.exit(-1);
}
try{
StringBuilder sb = new StringBuilder();
String line = null;
while((line=datainputstream.readLine())!=null){
sb.append(line+"\n");
}
datainputstream.close();
System.out.println("message:"+sb.toString());
}catch(IOException e){
System.out.println("Cant read file \n");
}finally{
if(socket!=null){
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(datainputstream!=null){
try{
datainputstream.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
here is the my client
Client side code
var net = require('net');
var client = net.connect(8888, 'localhost');
client.write('Hello from node.js');
client.end();
How do you code a chat client so that it listens for input both from the server and from the console? This is my current client which successfully sends to and accepts input from the server. As you can see, it doesn't have any code that will enable it to successfully listen for and accept input from the console while also being open to input from the server. The server input would be messages from other chat clients. A message sent from any chat client is broadcast to all other clients. I am pretty new to Java and am completely stuck even though I have a feeling the answer will be depressingly obvious.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClientMain
{
public static void main(String[] args) throws UnknownHostException, IOException
{
//DNS of Chat Server
final String HOST = "localhost";
//Port number for chat server connection
final int PORT = 6789;
Socket serverSocket = new Socket(HOST, PORT);
try
{
//Will need three streams for communication: console-client, client-server, server-client
PrintWriter toServer = new PrintWriter(serverSocket.getOutputStream(), true);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
//User must be logged in; any username is acceptable
System.out.print("Enter username > ");
toServer.println("LOGIN " + fromUser.readLine());
String serverResponse = null;
while((serverResponse = fromServer.readLine()) != null)
{
System.out.println("Server: " + serverResponse);
if(serverResponse.equals("LOGOUT"))
{
System.out.println("logged out.");
break;
}
System.out.print("command> ");
toServer.println(fromUser.readLine());
}
toServer.close();
fromServer.close();
fromUser.close();
serverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
If your main thread is listening to the input from the server, you may start another thread that would keep listening for input from the console. You will have to ensure that you handle input properly. Some flag may be set to indicate if the input is from the server or from the console.