Client program response with http request - java

Update: Thanks #MartinFrank for the idea, I added the http header to the result, and it works.
HTTP/1.1 200 OK Content-Type: text/html Content-Length: result.length()
I am working on a client program to work with the web application. the web server application will send a 'get' request to the client. then the client program will start to listen to the COM port which connected with a scale device and return the result weight as string back to the web server application.
I try to test the program with sending request with ARC client
http://localhost:8083/test
the system able to print
Listening for connection on port 8083 ....
Just connected to /0:0:0:0:0:0:0:1:50346
GET /test HTTP/1.1
HOST: localhost:8083
result ??? 3 741g
but the request is keep hanging on the requesting stage without response result like the picture below:
ARC client
any idea to get the proper response from the client program ? Thanks for the help.
static public void main(String[] args)
{
ServerSocket server;
try {
server = new ServerSocket(8083);
System.out.println("Listening for connection on port 8083 ....");
while (true) {
Socket clientSocket = server.accept();
System.out.println("Just connected to " + clientSocket.getRemoteSocketAddress());
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty()) {
System.out.println(line);
line = reader.readLine();
}
String result = openConnection();.//listen to COM port and return weight result.
var pw = new PrintWriter(clientSocket.getOutputStream(), true);
System.out.print(" result ??? "+result);
pw.println(result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String openConnection()
{
if(comPort == null || !comPort.isOpen()) {
comPort = SerialPort.getCommPorts()[0];
comPort.setComPortParameters(2400,7,SerialPort.ONE_STOP_BIT,SerialPort.EVEN_PARITY);
comPort.openPort();
System.out.println("COM port open: " + comPort.getDescriptivePortName());
}else {
System.out.println("COM port already open: " + comPort.getDescriptivePortName());
}
while(fullWeight == null) {
fullWeight = getWeight();
}
return fullWeight;
}
Also tried to hard code the result and remove the port functions.
static public void main(String[] args)
{
....
//String result = openConnection();
String result = "OK";
var pw = new PrintWriter(clientSocket.getOutputStream(), true);
pw.println(result);
}
} catch (IOException e) {
e.printStackTrace();
}
}

I think you need to flush your PrintWriter to effectively send your respone
pw.println(result);
pw.flush();

Related

Java Client not receiving C# Server response TCP

Can somebody explain to me what I am doing wrong.First time I try to implement TCP between Java and C#:
Sever code c#
`
public void CreateServer()
{
Thread thread = new Thread(() =>
{
IPAddress addr = IPAddress.Parse(localIP);
tcpListener = new TcpListener(addr, 5053);
if (tcpListener != null)
{
tcpListener.Start();
while (!end)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
var ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
Console.WriteLine("Client connected from "+ip);
NetworkStream clientStream = tcpClient.GetStream();
StreamReader reader = new StreamReader(clientStream, Encoding.UTF8);
try
{
string request = reader.ReadToEnd();
Console.WriteLine("Message from client: " + request);
Byte[] StringToSend = Encoding.UTF8.GetBytes("Server");
clientStream.Write(StringToSend, 0, StringToSend.Length);
Console.WriteLine("Sending response back");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
});
thread.Start();
}
`
Client code java
`
public class TCP {
private String IP;
private InetAddress server;
private Socket socket;
public TCP(String IP) {
this.IP = IP;
}
protected void runTCP() {
try {
server = InetAddress.getByName(IP);
socket = new Socket(server, 5053);
System.out.println("Client connected. Listening on port 5053");
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessage(String message) {
try {
System.out.println("Sending data...");
if (socket.isClosed()) socket = new Socket(server, 5053);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.print(message);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void getResponseServer() {
Thread thread = new Thread() {
#Override
public void run() {
try {
System.out.println("Attempting to get response...");
if (socket.isClosed()) socket = new Socket(server, 5053);
BufferedReader mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String mServerMessage = mBufferIn.readLine();
System.out.println("Server message: " + mServerMessage);
} catch (Exception e) {e.printStackTrace();}
}
};
thread.start();
}
}
`
Output on server I get when sending "Hello" from client to server:
Client connected from 192.16.... Message from client: Hello Sending response back Client connected from 192.16....
Output on client:
Client connected. Listening on port 5053 Sending data... Attempting to get response...
Never gets response... Why?
Tried researching but found nothing yet, tried other code but didnt work aswell...
sorry , I can't comment. maybe you can use telnet command to vertify c# code is corrent.
telnet ip port
first, locate problem, then solve it.
if server is ok , we can use nc command vertify client code, I have test your java code , except every send data will close socket , other is ok.
Fixed it by removing writer.close() cause that causes socket closing and makes another connection to the server by creating again the socket which makes the server wait for a stream of data and the client wait for a response...
System.out.println("Sending data...");
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
writer.println(message);
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

Trying to make send a message when the enter key is pressed

I am trying to send a message to the server. My problem is that the client keeps waiting for input and never sends it to the server until the last message that tells it to terminate (which is "bye"). After client terminates, the server will receive the message. But I want the server to receive the message everytime the client hit's the enter key.
I am not sure, but I think that the problem is with the Bufferedwriter in the client, because if I connect to the server using the browser, the server receives all the browser information. An example is shown below:
Connect to this server name: localhost and port: 121
Connection from client: Socket[addr=/0:0:0:0:0:0:0:1,port=61942,localport=121]
From client > GET / HTTP/1.1
From client > Host: localhost:121
From client > Connection: keep-alive
From client > Cache-Control: max-age=0
From client > Upgrade-Insecure-Requests: 1
From client > User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36
...
Relevant server code:
try {
sers = new ServerSocket(port);
client = sers.accept();
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
boolean clientIsOnline = true;
while (clientIsOnline) {
print("Connection from client: " + client);
while((msg = reader.readLine()) != null) {
print("From client > " + msg);
if(msg.toLowerCase().equals("bye"))
print("Client left, server closed");
clientIsOnline=false;
}
ss.close();
reader.close();
writer.close();
}
} catch(Exception e) {
print("Error starting server: ");
e.printStackTrace();
}
Relevant client code:
public Client(String adr, int port) {
this.adr=adr;
this.port=port;
try {
c=new Socket(adr, port);
r = new BufferedReader(new InputStreamReader(c.getInputStream()));
w = new PrintWriter(new OutputStreamWriter(c.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
Client method for sending the message
private void msgToServer(String msg) {
try {
w.write(msg);
w.flush();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(msg.toLowerCase().equals("bye")) {
print("I am out, bye");
try {
c.close();
r.close();
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client main method:
public static void main(String[] args) {
int port=121;
String msg =null;
Scanner sc = new Scanner(System.in);
Client c = new Client("localhost", port);
System.out.println("Write something to server");
while(true) {
c.msgToServer(sc.next());
}
}
I also tried using the PrintWriter instead of BufferedWriter, and also tried adding the true keyword as parameter, like
new PrintWriter(new OutputStreamWriter(c.getOutputStream()), true);
Just to give an example of what it looks like using my client.
I type hello hit enter (I expect it to send this, but it doesn't). Then I type my name is john hit enter again. Finally I type bye
I excpect:
From client > hello
From client > my name is john
From client > bye
What I get: From client > hellomynameisjohnbye
I believe the newline is being consumed when the client reads the input, so it needs to be added when sent to the server. In the client method:
private void msgToServer(String msg) {
try {
// re-introduce newline:
w.println(msg);
[SNIP]

Connect to localhost with java but nothing happened but it works with nodejs client file

I am trying to connect to localhost with a java app, and I have a server side code with nodeJS and.It's my first time to deal with nodeJS, when I created a server.js and client.js every thing was working correctly and I could send and receive messages to and from the server but when I tried to use java code(Socket) nothing happened but there is no errors. I can't find the reason and it's my first time I use nodeJS so I feel stuck, can any one give me advises or find out where is my mistake.
Here is my java code
String hostName = "localhost";
int portNumber = 8081;
try {
System.out.println("Connecting to " + hostName + " on port " + portNumber);
Socket client = new Socket(hostName, portNumber);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
out.writeInt(5);
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e) {
e.printStackTrace();
}
And here is my server code with nodeJS
var http = require('http');
var fs = require('fs');
var url = require('url');
// Create a server
http.createServer( function (request, response) {
var b = new Buffer("Return something");
response.write(b.toString());
console.log('listening to client');
response.end();
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
And here is my client code with nodeJS, it works fine
var http = require('http');
// Options to be used by request
var options = {
host: 'localhost',
port: '8081',
path: '/index.htm'
};
// Callback function is used to deal with response
var callback = function(response){
// Continuously update stream with data
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// Data received completely.
console.log(body);
});
}
// Make a request to the server
var req = http.request(options, callback);
req.end();
Try this ...
String hostName = "127.0.0.1";
int portNumber = 8081;
try {
System.out.println("Connecting to " + hostName + " on port " + portNumber);
Socket client = new Socket(hostName, portNumber);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
//OutputStream outToServer = client.getOutputStream();
//DataOutputStream out = new DataOutputStream(outToServer);
PrintWriter pw = new PrintWriter(client.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: 127.0.0.1");
pw.println()
pw.println("<html><body><h1>Hello world<\\h1><\\body><\\html>")
pw.println()
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
String t;
while((t = br.readLine()) != null) System.out.println(t);
br.close();
}catch(IOException e) {
e.printStackTrace();
}
To access an HTTP resource in Java, you don't need to use the socket API, which is too low-level. You are not using it in the NodeJS client code.
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class Http {
public static String get(String url) throws IOException {
try (Scanner scanner = new Scanner(new URL(url).openStream())) {
return scanner.useDelimiter("\\A").next();
}
}
}
Then you can use it like this:
try {
String content = Http.get("http://localhost:8080/index.htm");
} catch (IOException e) {
e.printStackTrace();
}

Java Server Client communication seems to stuck

Hello stackoverflow community,
i am stuck at a problem regarding socket communication in Java.
Here is the sample code of my Server and Client class:
Server:
public class OTPServer {
static ServerSocket serverSocket;
final static int PORT = 4242;
static Socket clientConnection;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Socket initialized");
String serverMessage = "Hello, I am the Host";
ServerTool serverTool = new ServerTool();
while (true) {
clientConnection = serverSocket.accept();
if(clientConnection.isConnected()) {
System.out.println("Client connected");
}
BufferedReader clientInputReader = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
DataOutputStream serverOutput = new DataOutputStream(clientConnection.getOutputStream());
System.out.println("Sending message to client: " + serverMessage);
serverOutput.writeBytes(serverTool.encodeMessage(serverMessage));
serverOutput.flush();
String clientMessage = clientInputReader.readLine();
System.out.println("Encoded answer from client: " + clientMessage);
String decodedMessage = serverTool.decodeMessage(clientMessage);
System.out.println("Decoded answer from client: " + decodedMessage);
serverOutput.close();
clientInputReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Hello, I am the OTP Server!");
}
Here is the Client:
public class OTPClient {
static Socket clientSocket;
final static int PORT = 4242;
final static String HOST = "localhost";
public static void main(String[] args) {
System.out.println("I am the OTP Client!");
String serverMessage;
String clientResponse = "I am the Client";
OTPTool otpTool = new OTPTool();
try {
clientSocket = new Socket(HOST, PORT);
BufferedReader serverInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Connection to Host established");
serverMessage = serverInput.readLine();
System.out.println("Encoded Message from Server: " + serverMessage);
String decodedMessage = otpTool.decodeMessage(serverMessage);
System.out.println("Decoded message from Server: " + decodedMessage);
System.out.println("Answering with own message: " + clientResponse);
outputStream.writeBytes(clientResponse);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Now where is my problem:
The connection establishes and the Server seems to send its message to the client and waits for a answer. The Client does not print the message he got from the Server.
As soon as i cancel the Server the client prints the message it gets from the server as well as the information, that the answer is send end exits with exit code 0 so it seems that this part is fine it just is stuck somehow.
I already tried to flush the outputStream as you see in the example code given.
Is there something obvious im missing?
I know, this is really basic stuff but its my first time using sockets for communication.
Thank you in advance!
Best Regards,
Ronny
Btw: i know that the server only connects to one client requesting a connection. Thats absolutely sufficient for my use.
It is getting stuck because serverInput.readLine(); blocks until either a line break or end of file is encountered. On the server side, you are not sending a line break, so the client blocks.

Proxy server does not get response from server

This is my first time making a web server. I want to create a proxy server. For now, I'm setting the server to "www.google.com" and not doing any parsing of HTTP requests.
I run ProxyServer on command line, then I call the server using "telnet server_name 5000" on another command line window, followed by "GET / HTTP/1.1".
Everything works until the while loop that handles the server's response. Nothing gets printed out. Why is that so?
All help appreciated.
import java.net.*;
import java.io.*;
public class ProxyServer {
public static void main(String[] args) throws IOException {
int proxyServerPortNumber = 5000;
String hostName = "www.google.com";
int portNumber = 80;
try {
// SERVER
// Open socket connection and bind it to proxyServerPortNumber
ServerSocket serverSocket =
new ServerSocket(proxyServerPortNumber);
// Listen and accept request
Socket clientSocket = serverSocket.accept();
System.out.println("client request accepted");
// send to client socket
PrintWriter sendToClient =
new PrintWriter(clientSocket.getOutputStream(), true);
// get from client socket
BufferedReader getFromClient = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
// CLIENT
// open socket connection
Socket echoSocket = new Socket(hostName, portNumber);
// send to server
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
// get from server
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
String clientRequest;
// clientRequest = "GET / HTTP/1.1\r\n\r\n";
while ((clientRequest = getFromClient.readLine()) != null) {
System.out.println("in while loop");
System.out.println(clientRequest);
out.println(clientRequest); // send to server
System.out.println("sent to server");
//Get response from server
String response;
while ((response = in.readLine()) != null) // no response why?
{
sendToClient.println("echo: " + response);
System.out.println("echo:" + response);
}
} // end while loop
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
The backslash in your HTTP request should be a forward slash.

Categories