run server socket code in background and then run client code - java

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.

Related

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

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.

My Java Server/Client program will only work every third time I run it

I am new to Java Programming, and even newer to Java Networking Programming, so I am sure the problem will be a simple one. My program is based around a submit button which submits the student ID to the server.
The first two times I run the program it will establish a connection with the server and then everything will crash and it will never exchange strings.
However, every third time I run it, it will work perfectly and exchange the strings as designed.
Client:
String currentButton = e.getActionCommand();
if(currentButton == "submit"){
try{
Socket server = new Socket("Localhost",1234);
InetAddress address=InetAddress.getLocalHost();
System.out.println("Connected to "+server.getInetAddress());
System.out.println("Connected to "+address);
BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter pw = new PrintWriter(server.getOutputStream(), true);
pw.println(student);
while ((student = br.readLine()) != null) {
System.out.println(student);
pw.println("bye");
if (student.equals("bye"))
break;
}
br.close();
pw.close();
server.close();
} catch (IOException ex){
//ignore exception
}
}
Server
class NETCW1S {
public static void main(String[] args) throws IOException {
String student;
ServerSocket serverSock = null;
InetAddress address=InetAddress.getLocalHost();
try{
serverSock = new ServerSocket(1234);
System.out.println("Waiting for client connection");
} catch (IOException e) {
System.err.println("Could not listen on port: 1234");
System.exit(1);
}
Socket clientSock = null;
try{
clientSock = serverSock.accept();
} catch (IOException e) {
System.err.println("Accept Failed");
System.exit(1);
}
while (true) {
System.out.println("Connected to "+address);
System.out.println("Waiting for client...");
Socket client = serverSock.accept();
System.out.println("Client from "+client.getInetAddress()+" connected.");
Socket fromClientSocket = serverSock.accept();
PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(fromClientSocket.getInputStream()));
while ((student = br.readLine()) != null) {
System.out.println("The message: " + student);
if (student.equals("bye")) {
pw.println("bye");
break;
} else {
student = "Server returns " + student;
pw.println(student);
}
}
pw.close();
br.close();
fromClientSocket.close();
}
}
Many thanks in advance!
The server should only have one accept() call, inside the loop. The client needs to make a connect() call at some point - right now it doesn't appear to be talking to the client at all.

Java sockets send and receiving data

Hi I am trying to understand how Sockets work can implement a multiplayer side to a monopoly game.I understood how to create the connection, but now it seems I have trouble sending and receiving the data between the client and the server .Here is my code:
Client code:
public class EchoClient
{
public static void main(String[] args)
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
echoSocket = new Socket("127.0.0.1", 5000);;
out = new PrintWriter(echoSocket.getOutputStream());
in = new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host: taranis");
}
catch (IOException e)
{
System.err.println("Couldent get I/O for "
+ " the connection to : taranis.");
}
}
}
Server code:
public class ServerSide
{
ServerSocket connect;
Socket connection;
PrintWriter out;
BufferedReader in;
public void go()
{
try
{
connect = new ServerSocket(5000);
connection = connect.accept();
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String userInput;
while ((userInput = in.readLine()) != null)
{
System.out.println("echo: " + in.readLine());
}
}
catch (IOException e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
new ServerSide().go();
}
}
I was trying to create here a simple connection between a client and a server.On the client side when the user inputs data I want it to be sent to the server and then print it it on the server console.It seems that the way I wright the code it isent working what did I do wrong?
First of all you need to declare a console object and then print on it.
Then don't forget to:
After every print on the console at the server side you need to flush the stream so the all the data will be printed.
Your code looks fine to me. Usually with sockets and keyboard input, you run into the case where the reader.readLine() hangs because it is still trying to read input from the other side. Typically, i will put an empty out.println() at the end of my client so the server will terminate the reading while loop. I've tried flush() before as Mike suggested but that seems to not work for me.
On the client, you're missing out.flush; after the out.println.
On the server,
while ((userInput = in.readLine()) != null) {
System.out.println("echo: " + userInput); // not in.readLine
}

Using sockets in Java with a proxy

I'm writing a very simple transport simulation (please don't ask why I use this approach, it's not really the point of my question).
I have three threads running (although you could consider them as seperate programs). One as a client, one as a server, and one as a proxy.
The first is used as the client, and the main code for that is given here:
try {
Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(InetAddress.getLocalHost(), 4466));
Socket socket = new Socket(proxy);
InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getLocalHost(), 4456);
socket.connect(socketAddress);
// send data
for (String straat : straten) {
socket.getOutputStream().write(straat.getBytes());
}
socket.getOutputStream().flush();
socket.getOutputStream().close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
The second is the server side, given here:
public void run() {
try {
ServerSocket ss = new ServerSocket(4456);
Socket s = ss.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
String incoming;
while ((incoming = in.readLine()) != null) {
panel.append(incoming + "\n");
}
panel.append("\n");
s.getInputStream().close();
s.close();
ss.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
And then there's the proxy-thread:
public void run() {
try {
ServerSocket ss = new ServerSocket(4466);
Socket s = ss.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
panel.append(verzenderId + "\n");
String incoming;
while ((incoming = in.readLine()) != null) {
panel.append(incoming + "\n");
}
panel.append("\n");
s.getInputStream().close();
s.close();
ss.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Somehow, this won't work. The message is sent directly to the server, and the proxy doesn't receive any socket request.
How can I make this work so that port 4466 becomes a proxy for the communication between the client-thread and the server-thread?
The goal is to make this socket between the client and the server to become an SSLSocket, so that the proxy can't read anything that goes over it. Therefore, setting up two sockets, one between the client and the proxy and one between the proxy and the server, is not the solution I'm looking for.
Thanks a lot in advance.

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