Socket connection to Heroku java server not working? - java

I have a simple Java server deployed on Heroku and I want to connect and send strings to and from it using Sockets from a client however I get no response when I send strings.
I have tried changing the port number from 80 to 443.
The server on Heroku:
public class Server {
public static void main(String[] args) throws IOException {
Integer port = Integer.parseInt(System.getenv("PORT"));
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while((inputLine = in.readLine())!=null) {
out.println(inputLine);
}
}
}
The client on my computer:
public class Client {
public static void main(String[] args) throws IOException {
try {
Socket echoSocket = new Socket("minimal-java-web-app.herokuapp.com", 80);
BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
String inputLine;
out.println("Sent this message to server");
while((inputLine = in.readLine())!=null) {
System.out.println("got message: "+inputLine);
}
echoSocket.close();
}
I expected an output of "got message: Sent this message to server" in the console when I run the client but I get nothing. No error or server response.

Related

How to get Java TCP Server and Client application to loop until a certain number of requests have been made

I've written both a TCP server and a TCP client application in eclipse. The Client gets user input in the form of a string then sends it to the server who capitalizes it and sends it back. They need to keep looping until the server has received a certain number of requests in which case it closes the connection between he sockets and stops. Unfortunately it only seems to loop once. I will provide a sample output of what I'm talking about after the code.
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
int requests = 0;
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader (new InputStreamReader( connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
do {
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
outToClient.flush();
requests++;
}
while(requests < 10);
outToClient.writeBytes("REQUEST LIMIT REACHED");
}
}
}
and the client
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
//Creates socket, replace the hostnmae/ip address with the ipaddress of the computer running the server application.
Socket clientSocket = new Socket("10.69.88.130", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader (clientSocket.getInputStream()));
do {
System.out.print("TO SERVER: ");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
outToServer.flush();
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
}
while (!modifiedSentence.equals("REQUEST LIMIT REACHED"));
System.out.println(modifiedSentence);
clientSocket.close();
}
}
and finally the output I'm getting
TO SERVER: testa
FROM SERVER: TESTA
TO SERVER: testb
(nothing else is displayed after this line)
Well your code is working (kind of). You get a successful run, then you restart your client without restarting the server. Your request-value does not reset to 0 and after restarting the client the first request your client does is number 10 for your server.
So why is that request comming through? Because you flush the string first and then check your counter.
I have modified your server a little bit. Maybe that is what you are looking for?
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
int requests = 0;
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader (new InputStreamReader( connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream());
while (requests < 10) {
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase();
outToClient.writeBytes(capitalizedSentence + " Request: " + requests + '\n');
outToClient.flush();
requests++;
}
outToClient.writeBytes("REQUEST LIMIT REACHED");
requests = 0;
}
}
}

Android TCP server recieves all data on application exit

I'm having the following TCP client code:
public static void register(InetAddress ip, int port, String name) {
try {
Socket clientSocket = new Socket(ip, port);
send("reg:" + name);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void send(String str) {
try {
String sentence = str;
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(sentence);
} catch (IOException e) {
Log.e("CONNECT", e.getMessage());
}
}
They both are called in onClicks and i know that for sure.
I also have the following Server code:
public static void main(String argv[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(9876);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
outToClient.writeBytes("msg: Hello! kalin pedro");
}
}
When trying to send data to the server i don't get an exception, i also know that I'm connected to it because the application is crashing when i terminate the server application. The problem is that the server doesn't receive anything until i terminate the client application. Everything that i have tried to send until that moment is all received from the server at once. I looked at the network activity tab provided by Android Studio and there is a change when sending data, the server just doesn't receive it(or at least i don't see it receive it) until i terminate the client application.

Simple client server with loop messaging

I am trying to implement a simple client server program that will continuously exchange messages until client decides to stop. I found many tutorials on this topic, however I am struggling with implementing the loop correctly. The server processes the first request but does not process the others.
It is probably some silly mistake so please excuse me for asking such basic question - I am new to sockets. I would be glad for any help. I provide all the code (based on some example that I found):
Client:
public class Client {
public static void main(String argv[]) throws Exception {
talkWithServer();
}
private static void talkWithServer() throws UnknownHostException, IOException {
String sentence;
String serverResponse;
BufferedReader brClient = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 9000);
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader brServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(true) {
sentence = brClient.readLine();
out.writeBytes(sentence + '\n');
serverResponse = brServer.readLine();
System.out.println(serverResponse);
if (serverResponse.contains("<BYE>")) {
break;
}
}
clientSocket.close();
}
}
Server:
public class Server {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(9000);
Protocol protocol = new Protocol();
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
String response = protocol.processInput(clientSentence);
outToClient.writeBytes(response + '\n');
}
}
}
Protocol:
public class Protocol {
public String processInput(String theInput) {
String theOutput = "> " + theInput;
return theOutput;
}
}
I simplified the example for sake of easier debugging. Thanks for any tips!
My guess is line "Socket connectionSocket = welcomeSocket.accept();"
If I remember right, this will try to accept new client everytime, and since you are connecting just one, it will wait on that line forever in second iteration.
I suggest you paste that line before the while loop.
Try below
Socket connectionSocket = welcomeSocket.accept();
while (true) {
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
String response = protocol.processInput(clientSentence);
outToClient.writeBytes(response + '\n');
outToClient.flush();
}

Bufferedreader never null, while loop won't terminate

I'm making a program where a client uses a proxy to ask a server to retrieve content from an URL, so for example, the client types in "http://www.google.ca", and they get the html code from that webpage. I got it to work once, but I want to it work multiple times. I tried using loops but they never terminate, bufferedreader never seems to = null for the Proxy or Client class (the Server class works fine though). Any help would be greatly appreciated.
Here is my code
Client.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception {
Client serv = new Client();
serv.run();
}
public void run() throws Exception {
Socket sock = new Socket("localhost", 7777); //connects to Proxy
PrintStream ps = new PrintStream(sock.getOutputStream()); //output stream to Proxy
InputStreamReader ir = new InputStreamReader(sock.getInputStream()); //input stream from Proxy
BufferedReader br = new BufferedReader(ir);
Scanner scanner = new Scanner(System.in); //take input from keyboard
//user types in an URL, outputs content of URL
for(int i = 0; i < 100; i++) {
ps.println(scanner.nextLine());
String inputLine;
while((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
System.out.println("DONE");
}
sock.close();
scanner.close();
}
}
Proxy.java
import java.net.*;
import java.io.*;
public class Proxy {
public static void main (String[] args) throws Exception {
Proxy serv = new Proxy();
serv.run();
}
public void run() throws Exception {
ServerSocket ss = new ServerSocket(7777);
Socket sock = ss.accept();
//input and output streams to and from Client
InputStreamReader ir = new InputStreamReader(sock.getInputStream());
BufferedReader br = new BufferedReader(ir);
PrintStream psToClient = new PrintStream(sock.getOutputStream());
//input and output streams to and from Server
Socket sck = new Socket("localhost", 8888);
PrintStream ps = new PrintStream(sck.getOutputStream());
InputStreamReader irFromServer = new InputStreamReader(sck.getInputStream());
BufferedReader brFromServer = new BufferedReader(irFromServer);
//passes message from Client to Server, passes URL content from Server back to Client
for(int i = 0; i < 100; i++) {
String message = br.readLine();
ps.println(message);
System.out.println("Client wants me to tell Server he wants the content of: " + message);
String inputLine;
while((inputLine = brFromServer.readLine()) != null) {
psToClient.println(inputLine);
//psToClient.flush();
System.out.println(inputLine);
}
System.out.println("DONE");
}
sock.close();
ss.close();
sck.close();
}
}
Server.java
import java.net.*;
import java.io.*;
public class Server {
public static void main (String[] args) throws Exception {
Server serv = new Server();
serv.run();
}
public void run() throws Exception {
ServerSocket ss = new ServerSocket(8888);
Socket sock = ss.accept();
//input and output streams to and from Proxy
InputStreamReader ir = new InputStreamReader(sock.getInputStream());
BufferedReader br = new BufferedReader(ir);
PrintStream psToProxy = new PrintStream(sock.getOutputStream());
//retrieves content from requested URL and sends back to Proxy
for(int i = 0; i < 100; i++) {
String request = br.readLine();
System.out.println("Proxy told me Client wants the content from: " + request);
//makes URL object using String value from Client
URL url = new URL(request);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
//sends URL content back to Client, via Proxy
String inputLine;
while ((inputLine = in.readLine()) != null) {
psToProxy.println(inputLine);
//psToProxy.flush();
System.out.println(inputLine);
}
System.out.println("FINISHED SENDING CONTENT");
in.close();
}
sock.close();
ss.close();
}
}
bufferedreader never seems to = null
Your question is a little imprecise. What you mean is that BufferedReader.readLine() never returns null. That only happens when the peer closes the connection. If he never closes it, readLine() won't return null.
If you're writing an HTTP proxy you need to have a good look at RFC 2616, and specifically the requirements about the Content-length header, the Connection: close header, and chunked transfer encoding. Just reading the response stream to its end is in general not sufficient.

Java Client-Server application pipe not working on child thread

I have a client and a server. The client binds a socket on a specific port, the server sends back a new port to the client and the client should bind a new socket on the new port number.
From the main server thread, I start a thread that sends a message to the client once the server is ready and is listening to the new port, so that the client can attempt to connect to the new port. The pipe from the child thread is not sending the message to the client.
So both client and server just freeze, it seems like a deadlock, but im not sure. This line of code in the client: System.out.println("FROM SERVER: " + inMsg_rport); is not executing.
Server Code:
class server
{
public static void main(String argv[]) throws Exception
{
String newPort;
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(5555);
clientSocket = serverSocket.accept();
DataOutputStream serverOut =
new DataOutputStream(clientSocket.getOutputStream());
int r_port = 5556;
Thread appThread = new Thread(new serverApp(serverOut, r_port));
appThread.start();
}
catch(IOException e)
{
System.out.println(e);
}
}
static class serverApp implements Runnable
{
DataOutputStream serverOut;
int nPort;
public serverApp(DataOutputStream servO, int r_port)
{
this.serverOut = servO;
this.nPort = r_port;
}
#Override
public void run()
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(nPort);
serverOut.writeBytes(sr_port);
clientSocket = serverSocket.accept();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
}
Client code:
class client {
public static void main(String argv[]) throws Exception
{
String serverIp = argv[0];
String msg = argv[2];
int port = Integer.parseInt(argv[1]);
Socket clientSocket = new Socket(InetAddress.getByName(serverIp), port);
BufferedReader clientIn =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inMsg_rport = clientIn.readLine();
System.out.println("FROM SERVER: " + inMsg_rport);
int r_port = Integer.parseInt(inMsg_rport);
clientSocket.close();
System.out.println("Closed connection");
Socket new_clientSocket = new Socket(InetAddress.getByName(serverIp), r_port);
}
}
readLine() in your client is a blocking call, waiting for an end-of-line character
http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()
You aren't sending an end of line character. You're using a DataOutputStream in your server and sending raw bytes.
Don't use a DataOutputStream in your server; I don't think that's really what you're looking for. Just send the port number as text with an end of line character and be done with it.

Categories

Resources