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.
Related
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();
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();
}
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.
I'm trying to program a Server Client program where the CLIENT will be prompt if the SERVER closes or loses connection. What happens is once I connect the server and the client then disconnects the server it doesn't go to the ConnectException part
example: I opened the Server and Client connects, in the Client it will show that "You are connected to the Server", then if the Server disconnects there should be a "Server is disconnected". and when the Server reopens it will prompt the Client that he's connected to the Server
How can I continuously check if the Server is open or disconnected
here's my code:
SERVER
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
System.out.println("Client has connected!");
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
CLIENT
public class Client
{
private static Socket socket;
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
System.out.println("Connected to the Server");
}
catch (ConnectException exception)
{
System.out.println("Server is still offline");
}
catch(IOException ex)
{
System.out.println("Server got disconnected");
}
}
}
Well, the best way to tell if your connection is interrupted is to try to read/write from the socket. If the operation fails, then you have lost your connection sometime.
So, all you need to do is to try reading at some interval, and if the read fails try reconnecting.
The important events for you will be when a read fails - you lost connection, and when a new socket is connected - you regained connection.
That way you can keep track of up time and down time.
you can do like this
try
{
Socket s = new Socket("address",port);
DataOutputStream os = new DataOutputStream(s.getOutputStream());
DataInputStream is = new DataInputStream(s.getInputStream());
while (true)
{
os.writeBytes("GET /index.html HTTP/1.0\n\n");
is.available();
Thread.sleep(1000);
}
}
catch (IOException e)
{
System.out.println("connection probably lost");
e.printStackTrace();
}
or you can simply et connection time out like this socket.setSoTimeout(timeout); to check connectivity
or you can use
socket.getInputStream().read()
makes the thread wait for input as long as the server is connected and therefore makes your program not do anything - except if you get some input and
returns -1 if the client disconnected
or what you can do is structure your code in this way
while(isConnected())
{
// do stuffs here
}
I have the following Situation.
I have a Server class.
I have a Client class.
I have a MultiServerThread class.
When a Client connects to a Server, the Server creates a new MultiServerThread, which is processing the Input from the Client. That way I can have multiple Clients. So far so good.
The connection goes via TCP.
A short example:
Server class:
...
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(9999);
} catch (IOException e) {
System.err.println("Could not listen on port: " + serverSocket.getLocalPort() + ".");
System.exit(-1);
}
while (listening) {
new MultiServerThread(serverSocket.accept()).start();
}
serverSocket.close();
}
...
Client class:
...
public static void main(String[] args) throws IOException {
socket = new Socket(hostname, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye.")) {
break;
}
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
socket.close();
}
...
MultiServerThread class:
...
public MultiServerThread(Socket socket) throws SocketException {
super("MultiServerThread");
this.socket = socket;
// dSocket = new DatagramSocket(4445);
}
public void run() {
try {
PrintWriter myOutput = new PrintWriter(socket.getOutputStream(), true);
BufferedReader myInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
myOutput.println("Connected to client and ready to accept commands.");
while ((clientInput = myInput.readLine()) != null) {
//A SIMPLE LOGIN A USER
if (clientInput.contains("!login")) {
//save some string given by client into loggedUser
String loggedUser = clientInput.substring(7);
}
myOutput.close();
myInput.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
What I need is:
I need to implement a notification that comes from a Server when for example the Username is "Bob". If the username is "Bob", the server should give a notification to the Client "Bob is here again!". In my project/homework this should be done with datagrams in Java.
So if the clientinput is "!login bob" then a datagram packet with the message ("Bob is here again!") should be sent to the client.
Question: Where exactly should I put the code of the Datagram request in? Can I put the datagram packet request into the MultiServerThread or into the Client?
It would be easier in the MultiServerThread because it already handles the !login.
Here:
if (clientInput.contains("!login")) {
//save some string given by client into loggedUser
String loggedUser = clientInput.substring(7);
//send datagram request to Server???
}
But this is going against the principle of networking?
you need to send the UDP port number to your client through the initial TCP connection. Then you start listening for UDP datagrams on your client on that port number. All other communications from server -> client will be on this udp socket. This is what your assignment suggests
I got it working ;-)
I definied a udp port in the thread and client class...
the client class got his port with arguments... it gave the udp Port to the thread... so both had the udp ports ;)