how to connect Restful API and socket server in java - java

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);
}
}

Related

Java: Simple Client Server message exchange not working

I am new to Java just started yesterday. I wrote a very simple client server java code. Client sends a message to server. The Server should display that message. And the Server should send a message to client after receiving the message. The client should display the message sent by server.
Server Code,
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.net.Socket;
import java.net.ServerSocket;
public class CustomServer{
public static void main(String[] args){
final int SERVER_PORT_NUMBER = 8081;
try{
ServerSocket serverObj = new ServerSocket(SERVER_PORT_NUMBER);
Socket clientSocketObj = serverObj.accept();
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocketObj.getInputStream()));
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocketObj.getOutputStream()));
if(clientSocketObj != null){
System.out.println("Client Connected to Server!");
// Recieve Message from Client
System.out.println("MESSAGE FROM CLIENT");
System.out.println(clientInputStream.readLine());
// Send Message to Client
clientOutputStream.write("SERVER: Hello Client!");
// Close Streams
clientOutputStream.close();
clientInputStream.close();
}
serverObj.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Client,
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
public class CustomClient{
public static void main(String[] args){
final String HOST_NAME = "127.0.0.1";
final int SERVER_PORT_NUMBER = 8081;
try{
Socket clientSocket = new Socket(HOST_NAME, SERVER_PORT_NUMBER);
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Connecting....");
if(clientSocket != null){
System.out.println("Connected to Server!");
// Send message to Server
clientOutputStream.write("CLIENT: HELLO SERVER");
// Recieve message from Server
System.out.println("MESSAGE FROM SERVER");
System.out.println(clientInputStream.readLine());
// Close Streams
clientInputStream.close();
clientOutputStream.close();
}
clientSocket.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Neither the Server or Client receive the message. Stuck in some loop. Anyone know why?
Start by having a read of the BufferedReader's JavaDocs, which state
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed
BufferedWriter#write is not sending this, so the reader is still waiting.
A simply solution might be to use BufferedWriter#newLine after the write
And don't forget to flush the buffer when you're finished writing to it!
You may also want to take a look at try-with-resources which will provide a better resource management solution
CustomClient
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class CustomClient {
public static void main(String[] args) {
final String HOST_NAME = "127.0.0.1";
final int SERVER_PORT_NUMBER = 8081;
try (Socket clientSocket = new Socket(HOST_NAME, SERVER_PORT_NUMBER)) {
try (BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
System.out.println("Connecting....");
System.out.println("Connected to Server!");
// Send message to Server
clientOutputStream.write("CLIENT: HELLO SERVER");
clientOutputStream.newLine();
clientOutputStream.flush();
// Recieve message from Server
System.out.println("MESSAGE FROM SERVER");
System.out.println(clientInputStream.readLine());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
CustomServer
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class CustomServer {
public static void main(String[] args) {
final int SERVER_PORT_NUMBER = 8081;
try (ServerSocket serverObj = new ServerSocket(SERVER_PORT_NUMBER)) {
try (Socket clientSocketObj = serverObj.accept()) {
try (BufferedReader clientInputStream = new BufferedReader(new InputStreamReader(clientSocketObj.getInputStream()));
BufferedWriter clientOutputStream = new BufferedWriter(new OutputStreamWriter(clientSocketObj.getOutputStream()))) {
System.out.println("Client Connected to Server!");
// Recieve Message from Client
System.out.println("MESSAGE FROM CLIENT");
System.out.println(clientInputStream.readLine());
// Send Message to Client
clientOutputStream.write("SERVER: Hello Client!");
clientOutputStream.newLine();
clientOutputStream.flush();
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}

Issues with simple client server program

I have written two-way client-server communication in which client first sends the message and then server sends the reply. However, client is blocked while reading the reply sent by server( i.e Nothing is printed at client side however, server has sent the reply correctly). Below is the code :-
Server code:-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
// Socket for accepting connections.
private static Socket socket;
public static void main( String[] args )
{
try
{
int port = 2550;
// Creating server socket on specified port.
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started listening on port "+port);
while(true)
{
// Accept the connection and read the message.
socket = serverSocket.accept();
BufferedReader br = new BufferedReader( new InputStreamReader( socket.getInputStream()));
String message = br.readLine();
System.out.println("Message recieved from client is :- " + message);
// Prepare and send the response back to client.
BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream()));
String reply = "Thanks.Your reply has been recieved";
bw.write(reply);
bw.flush();
}
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch( Exception e )
{
}
}
}
}
Client code :-
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client
{
private static Socket socket;
public static void main( String[] args )
{
try
{
String host = "localhost";
int port = 2550;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
// Send the message to the server.
BufferedWriter bw = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream()));
String message = "This is the message from Client.\n";
bw.write(message);
bw.flush();
System.out.println("Message sent to the server :- " + message);
// Get the reply from the server.
BufferedReader br = new BufferedReader( new InputStreamReader( socket.getInputStream()));
String reply = br.readLine();
System.out.println("Message recieved from the server :- " + reply);
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
// Closing the socket.
try
{
socket.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
}
}
D:\Java_P>java Server
Server started listening on port 2550
Message recieved from client is :- This is the message from Client.
D:\Java_P>java Client
Message sent to the server :- This is the message from Client.
I
This is happening because your server sends "Thanks. Your reply has been recieved" which does not contain any newline character. Reason is because in the client, buffered reader readline method blocks till it finds a newline character.
Make following changes:
String reply = "Thanks.Your reply has been recieved\nDummy line 1";
Now you can see the lines in your client logs.

when I don't have access to the Server how can i close the socket Connection from client side?

/*after socket.close(); socket.isConnected() returns "true" why ? */
package example.servertest;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
public class ClientConn
{
public void startClient()
{
String serverName = "localhost";
int port = Integer.parseInt("8080");
Socket client = null ;
OutputStream outToServer = null ;
DataOutputStream out = null ;
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
client = new Socket(serverName,port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
outToServer = client.getOutputStream();
PrintWriter pw = new PrintWriter(outToServer);
pw.write("Hello ");
pw.flush();
pw.close();
/*out = new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());*/
/*InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());*/
}catch(IOException e)
{
e.printStackTrace();
}finally{
try {
/* out.flush();
out.close();
outToServer.flush();
outToServer.close(); */// closes the socket
/*client.shutdownInput();
client.shutdownOutput();*/
client.close();
System.out.println("isConnected : "+client.isConnected()+"\nisClosed : "+client.isClosed()+"\nisBound : "+client.isBound());
} catch (IOException e) {
}
}
}
}
Description :
The Above code creates a "Socket Connection" from Apache Server and then close it..but after closing the Socket from client side it returns "socket.isConnected() = true".. I don't understand why?
Socket.isConnected() tells you whether you ever connected the socket. You did, so it returns true. It doesn't tell you anything about the state of the connection, of which the socket is an endpoint. Only reading an EOS does that.
You don't need to worry about that. The link state will remain open for a while until it is being disposed. See Socket.isConnected in java doc:
public boolean isConnected()
Returns the connection state of the socket.
Note: Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket (see isClosed()) if it was successfuly connected prior to being closed.

Java server program doesn't accept the input from client at second run of client

I wrote a small client server program in Java. Server creates a ServerSocket on some port and keeps listening to it. Client sends some sample info to this server.
When I run Client the first time connection is accepted by server and info is printed by server. Then Client program exits. When I run Client again, connection is accepted however, data is not printed.
Please check following code.
Server Program
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(dis.available() > 0) {
System.out.println(dis.readByte());
}
}
}
}
Client Program
package javadaemon;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
} catch(IOException e) {
}
}
}
Please help me in finding why next time no data is received by server.
The reason is before server side receive data, the Client already exits, I just debug it. (Can't explain whey it works at the first time.)
Just change your code like the below, and it works.
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(true) {
try {
System.out.println(dis.readByte());
} catch (Exception e) {
break;
}
}
}
}
}
The Client must add flush before exits,
package javadaemon;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
out.flush();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
Place this in your Client program after for loop:
out.flush();
out.close();
client.close();
You need to flush your stream in order to push the data forward and clean the stream. Also, you will need to close your client socket.
I just tested this successfully.

How to Run Stand Alone Java Application from server to any Client

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.

Categories

Resources