how to run java server socket program (class file) in openshift - java

I want to run a socket program in my openshift server.
my action_hooks/start:-
#!/bin/bash
# The logic to start up your application should be put in this
# script. The application will work only if it binds to
# $OPENSHIFT_DIY_IP:8080
#nohup $OPENSHIFT_REPO_DIR/diy/testrubyserver.rb $OPENSHIFT_DIY_IP $OPENSHIFT_REPO_DIR/diy |& /usr/bin/logshifter -tag diy &
java -cp $OPENSHIFT_REPO_DIR/diy/EchoServer
my server program:-
import java.net.*;
import java.io.*;
public class EchoServer
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("xxx.xxx.xx.xx",8080));
}
catch (IOException e)
{
System.err.println("Could not listen on port: 8080.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
my client program:-
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("xxxxxxxxxxx.rhcloud.com");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 8080.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 8080);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
my log file "diy.log"
[2015-12-22 11:59:03] INFO WEBrick 1.3.1
[2015-12-22 11:59:03] INFO ruby 1.8.7 (2013-06-27) [x86_64-linux]
[2015-12-22 11:59:03] INFO WEBrick::HTTPServer#start: pid=44992 port=8080
[2015-12-22 12:05:36] INFO going to shutdown ...
[2015-12-22 12:05:36] INFO WEBrick::HTTPServer#start done.
I don't know the server program automatically start or not but when i run server program through ssh, the program is running but not responding to client.

It seems you are trying to connect to port 8080 with your client:
echoSocket = new Socket(serverHostname, 8080);
The server still needs to be bound to 8080 to be externally reachable, but clients should connect to 80 or 8000 (websockets) actually. See this diagram for details on how to route requests on OpenShift.
Check the terminal output when pushing code, to see whether your action hook that is launching the server works. Make sure to have the hook file executable.

Related

Not printing files content in socket programming

I am naive to this socket programming. I am trying to print the content of the file present in the directory in the server's console but the server is not able to locate the file.
Here is my code:
myClient.java
import java.net.*;
import java.io.*;
public class myClient {
public static void main(String args[]){
Socket socket = null;
String hostName,command,fileName;
int port;
if(args.length == 0){
System.out.println("Error: command line arguments (hostname,port,command,"
+ "filename) not found.\nTry again...!!!");
System.exit(1);
}
hostName = args[0];
port = Integer.parseInt(args[1]);
command = args[2];
fileName = args[3];
try{
socket = new Socket(hostName,port);
System.out.println("Client Socket Created..!!");
// creating input and output streams to read from and write to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
if(command.equals("GET")){
System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
bw.write(fileName);
String line = br.readLine();
while(line != null){
System.out.println("Server: "+line);
line = br.readLine();
}
}
if(command.equals("PUT")){
System.out.println("Client: "+fileName+" sent to server");
bw.write(fileName);
// pass the file contents
bw.flush();
System.out.println("Server: "+br.readLine());
}
}
catch(UnknownHostException uhe){
System.out.println("Unknown Host...!!!");
System.exit(1);
}
catch(IOException e){
e.printStackTrace();
}
finally
{
//Closing the socket
try{
socket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
myServer.java
import java.net.*;
import java.io.*;
public class myServer {
static Socket socket;
public static void main(String args[]){
try {
int port = Integer.parseInt(args[0]);
//String fileName = "";
ServerSocket server = new ServerSocket(port);
while(true)
{
System.out.println("Server started and listening on port "+port);
socket = server.accept();
System.out.println("received a connection :"+socket);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Echo server 1.1\n");
bw.flush();
String line = br.readLine();
while(line != null){
bw.write("Echo: "+line);
bw.flush();
line = br.readLine();
}
}
} catch (IOException e) {
System.out.println("No conncetion established");
System.exit(0);
//e.printStackTrace();
}
finally
{
//Closing the socket
try{
socket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
Kindly help me out finding a solution to this. I have tried many examples browsing different websites but not get to the solutions.
System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
bw.write(fileName);
You aren't writing a correct HTTP command to the server. You're only sending the filename, not a complete command such as the GET command you're printing to the console.
The line terminator in HTTP is specified as \r\n, not \n.
You're also making no attempt to implement other aspects of HTTP 1.1 correctly, such as content-length. If you're going to implement HTTP you need a good knowledge of RFC 2616.
If possible you should throw this away and use HttpURLConnection.

Java TCPSocket breaks after Client closes connection [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am very new to programming, especially to socket programming. I tried to figure out how communication works in real (not in all my books), but ran immediately into my first problem with the downloaded SimpleEchoServer example. Communicationflow works but when the Clientsocket closes his connection without sending a specific string, my serversocket breaks down. Can you please tell what have i've done wrong?
This is the server side:
import java.net.*;
import java.io.*;
import java.net.InetAddress;
public class EchoServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
Integer port = new Integer(args[0]);
try {
serverSocket = new ServerSocket(port);
}
catch (IOException e) {
System.err.println("Could not listen on port: "+port);
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection on port "+port+" ...");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println ("received: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
and that's the client side
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String (args[0]);
Integer port = new Integer(args[1]);
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " + serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream(), "UTF-8"));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
It is not the ServerSocket that breaks.
The EchoServer reads from the client socket's InputStream in the loop while ((inputLine = in.readLine()) != null). When the socket connection is terminated, attempting to read will throw an exception. Since the loop isn't inside a try-catch-block, the exception kills the server process.
To prevent that, you need to handle the exception.
try {
while ((inputLine = in.readLine()) != null) {
System.out.println ("received: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
}
} catch (IOException ex) {
System.out.println("Connection error... terminating.");
}

run server socket code in background and then run client code

After merging the code from two files (client and server) into into one, the control never reaches the client code anymore. However, I need to run server code in background and then run my client code.
Here is my code:
//Server code
try {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10007);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10007.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
//Client code
String serverHostname = new String ("127.0.0.1");
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10007.");
Socket echoSocket = null;
try {
echoSocket = new Socket(serverHostname, 10007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");
}
out.close();
try {
in.close();
stdIn.close();
echoSocket.close();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
I don't understand how to run my server code in background and then run my client code.
Use a public static class Client nested inside the main Server class. Each of them can have its own main method, so this is a way to achieve your goal of everything in one file, yet two separate entry points.
Another choice would be to have a single entry point but make it start two threads, one for the client and one for the server.
You need to make 2 classes:
One Client
One Server
Each one will have it's own main() method.
Like this you can start 2 JVM's one server, one Client
Or in one Class:
Create 2 static inner classes the implement Runnable and you start both from inside your main class: (i take the assumption here that your main class is called Starter)
public static main(String args [ ]) {
new Thread(new Starter.Server()).start();
new Thread(new Starter.Client()).start();
}
I will let you do the cleanup code...
Technically you could do this all in one source file by instantiating a thread that invokes the server code like this
// Start the Server
new Thread(new Runnable() {
public void run() {
// .. all the server code
}
}).start();
// Start the client
// .. all the client code
Behind the scenes, Java is probably creating anonymous inner classes for things like the new Runnable() { } technique.

Console based login application using java sockets

I am making a console based java application - which will check the username and password of client. What I want is the data entered by client must enter to server in a line by line format i.e pressing enter must send username data and password for next enter press. But what the problem is - until I quit at the client side the data is not sent to the server. Meaning , when client hits 'Bye.' then the client is closed and server receives the data then. Help me in this regard as this is the first step - later I have to check database with this username and password on server. My codes are as follows :
Server :
import java.net.*;
import java.io.*;
public class EchoServer2 extends Thread
{
protected Socket clientSocket;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(2010);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2 (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port.");
System.exit(1);
}
}
}
private EchoServer2 (Socket clientSoc)
{
clientSocket = clientSoc;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
PrintWriter out1 = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
BufferedReader in1 = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine,u,p;
while ((u = in.readLine()) != null && (p = in.readLine()) != null)
{
System.out.println ("U: " + u);
out1.println(u);
System.out.println ("P: " + p);
out1.println(p);
if (u.equals("Bye."))
break;
}
out1.close();
out.close();
//in1.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client :
import java.io.*;
import java.net.*;
import java.lang.*;
import java.io.Console;
public class EchoClient2 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port .");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader in1 = null;
try {
echoSocket = new Socket(serverHostname, 2010);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader std = new BufferedReader(
new InputStreamReader(System.in));
String upwd,uname,text;
Console console = System.console();
String username = console.readLine("Username:");
char[] pwd = console.readPassword("Password:");
upwd=new String(pwd);
while (username!=null && upwd!=null && (uname = stdIn.readLine()) != null)
{
out.println("Username:"+username);
out.println("Password:"+upwd);
// end loop
if (uname.equals("Bye."))
break;
}
out.close();
stdIn.close();
echoSocket.close();
}
}
On the client side, do out.flush() after writing the password to the stream.

question regarding Echoclient program

I am always getting the message Don't know about host: taranis. while running echoclient program. here is the program below
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("taranis",3218);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
You need to use a valid host name, or a valid IP of your server (assuming you have one) when you initialize your socket (new Socket("taranis",3218) ). It is great to take those tutorials (as pointed by icktoofay), but especially when it comes to networking, you have to make sure you have the matching application running on the other side, and that the parameters match it. IP and port usually change from machine to machine and from application to application.

Categories