How to run each client on new thread with ExecutorService Java? - java

I am implementing HTTP server on vanilla Java. And I try to use ExecutorService.
First request is successful in browser, but second one has endless loading.
Code of my start() method of server:
public void start() throws IOException {
this.server = new ServerSocket(this.port);
ExecutorService executor = Executors.newCachedThreadPool();
client = this.server.accept();
while (true) {
executor.submit(() -> {
Socket cs = client;
try (PrintWriter out = new PrintWriter(cs.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()))
) {
// write server http headers response
out.print("HTTP/1.1 200 OK \n");
out.print("Content-Type: text/plain\n");
out.print("Accept-Language: en-US, en; q=0.5\n");
// out.print("Connection: close\n");
out.print("\n");
String data;
// read client request
while ((data = in.readLine()) != null) {
if (data.length() == 0) {
out.write("EOF(End of file)");
break;
}
// write back to client its request as response body.
out.write(data + "\n");
}
out.close();
in.close();
cs.close();
} catch (IOException e) {
e.getMessage();
}
});
}
}
What I am doing wrong?

use this code i hope it's going to help you
after catch use finally to close in
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("D:\\DukesDiary.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
System.out.println(strCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
update
PrintWriter pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8"),true);

Related

Android Client Socket IOException

EDIT: The problem is the input in the Client.class so when the Android devices receives an answer from the Server. Those are the following lines that causes the crash:
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String text;
while ((text = reader.readLine()) != null) {
Log.d("ClientLog", "Received from Server"+ text);
}
Here is my Client.class in Android:
public class Client implements Runnable{
public Client() {
}
#Override
public void run() {
try {
Log.d("ClientLog", "Socket creation incoming");
Socket client = new Socket("localhost", 5555);
Log.d("ClientLog", "Client has been started");
// Streams:
OutputStream out = client.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
// -----------------------------------------------------------------------
writer.write("Test");
writer.newLine();
writer.flush();
String text;
while ((text = reader.readLine()) != null) {
Log.d("ClientLog", "Received from Server"+ text);
}
writer.close();
reader.close();
} catch (UnknownHostException e) {
Log.d("ClientLog", "Error: Host not found");
e.printStackTrace();
} catch (IOException e) {
Log.d("ClientLog", "Error: IOException");
e.printStackTrace();
}
}
}
And if needed my Server.class in Java:
public class Server {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(30);
ServerSocket server;
try {
server = new ServerSocket(5555);
System.out.println("Server has been started on Port 5555");
while(true) {
try {
Socket client = server.accept();
//Thread t = new Thread(new Handler(client));
//t.start();
executor.execute(new Handler(client));
} catch (IOException e) {
System.out.println("Error IOExceotion");
e.printStackTrace();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
The Handler.class needed for Server.class:
public class Handler implements Runnable{
private Socket client;
public Handler(Socket pClient) {
client = pClient;
}
#Override
public void run() {
try {
// Streams:
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
// -----------------------------------------------------------------------
String text = null;
while ((text = reader.readLine()) != null) {
writer.write(text+ "\n");
writer.flush();
System.out.println("Recieved from Client: "+ text);
}
//Close Streams
writer.close();
reader.close();
client.close();
} catch (IOException e) {
System.out.println("Error IOException");
e.printStackTrace();
}
}
}
The debugging was resolved in the comments above.
Step 1: Add permissions to the android manifest file as was outlined here: Java socket IOException - permission denied
Step 2: Change the while ((text = reader.readLine()) != null) check. I guess the text = reader.readLine() != null check was problematic.

Multithreaded proxy application is not working

I'm trying to create a proxy application, but I'm facing problems in server socket. The Server Socket is not accepting the connection and returning a socket. Hence, I cannot test the proxy application. What is wrong?
The problem line is indicated in WebServe.java:
public class WebServe implements Runnable {
Socket soc;
OutputStream os;
BufferedReader is;
String resource;
WebServe(Socket s) throws IOException {
soc = s;
os = soc.getOutputStream();
is = new BufferedReader(new InputStreamReader(soc.getInputStream()));
}
public void run() {
System.err.println("Running");
getRequest();
returnResponse();
close();
}
public static void main(String args[]) {
try {
System.out.println("Proxy Thread");
ServerSocket s = new ServerSocket(8080);
for (;;) {
s.setSoTimeout(10000);
WebServe w = new WebServe(s.accept()); // Problem is here
Thread thr = new Thread(w);
thr.start();
w.getRequest();
w.returnResponse();
w.close();
}
} catch (IOException i) {
System.err.println("IOException in Server");
}
}
void getRequest() {
System.out.println("Getting Request");
try {
String message;
while ((message = is.readLine()) != null) {
if (message.equals("")) {
break;
}
System.err.println(message);
StringTokenizer t = new StringTokenizer(message);
String token = t.nextToken();
if (token.equals("GET")) {
resource = t.nextToken();
}
}
} catch (IOException e) {
System.err.println("Error receiving Web request");
}
}
void returnResponse() {
int c;
try {
FileInputStream f = new FileInputStream("." + resource);
while ((c = f.read()) != -1) {
os.write(c);
}
f.close();
} catch (IOException e) {
System.err.println("IOException is reading in web");
}
}
public void close() {
try {
is.close();
os.close();
soc.close();
} catch (IOException e) {
System.err.println("IOException in closing connection");
}
}
}
public static void main(String args[]){
try {
System.out.println("Proxy Thread");
ServerSocket s = new ServerSocket (8080);
for (;;){
s.setSoTimeout(10000);
Move that ahead of the loop. You don't need to keep setting it. You don't really need it at all actually.
WebServe w = new WebServe (s.accept()); //Problem is here
The problem is here only because you set a socket timeout you don't actually need.
Thread thr = new Thread (w);
thr.start();
So far so good.
w.getRequest();
w.returnResponse();
w.close();
Remove. The next problem is here. The run() method of WebServ already does this.
As to the rest, you aren't writing an HTTP header in the response.

how to detect client's Internet speed from the response headers in java?

I have a server to get a response headers through which I detect the type of device. Is there any way I can get the Internet speed through response headers or any other method ?
Server_X:
public class Server_X {
static int count = 0;
public static void main(String args[]) {
Socket s = null;
ServerSocket ss2 = null;
System.out.println("Server Listening......");
try {
// can also use static final PORT_NUM, when defined
ss2 = new ServerSocket(4445);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Server error");
}
while (true) {
try {
s = ss2.accept();
System.out.println("connection Established");
ServerThread st = new ServerThread(s);
count++;
System.out.println("total connections :" + count);
st.start();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
ServerThread:
class ServerThread extends Thread {
static String uagent, uaccept;
static String[] b;
static String[] c;
Server_X obj = new Server_X();
String line = null;
BufferedReader is = null;
PrintWriter os = null;
Socket s = null;
public ServerThread(Socket s) {
this.s = s;
}
public void run() {
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = new PrintWriter(s.getOutputStream());
} catch (IOException e) {
System.out.println("IO error in server thread");
}
try {
line = is.readLine();
while (line.compareTo("QUIT") != 0) {
os.println(line);
os.flush();
// System.out.println(line);
line = is.readLine();
b = line.split(":");
if (b[0].equals("User-Agent")) {
uagent = b[1];
// System.out.println(uagent);
}
c = line.split(":");
if (c[0].equals("Accept")) {
uaccept = c[1];
// System.out.println(uaccept);
}
UAgentInfo detect = new UAgentInfo(uagent, uaccept);
}
} catch (IOException e) {
line = this.getName(); // reused String line for getting thread name
// System.out.println("IO Error/ Client "+line+" terminated abruptly");
} catch (NullPointerException e) {
line = this.getName(); // reused String line for getting thread name
// System.out.println("Client "+line+" Closed");
} finally {
try {
System.out.println("Connection Closing..");
if (is != null) {
is.close();
// System.out.println(" Socket Input Stream Closed");
}
if (os != null) {
os.close();
// System.out.println("Socket Out Closed");
}
if (s != null) {
s.close();
// System.out.println("Socket Closed");
obj.count--;
System.out.println("Toatal connections (after closing):"
+ obj.count);
}
} catch (IOException ie) {
// System.out.println("Socket Close Error");
}
}// end finally
}
}
You didn't specify what protocol the server is using; I suppose is HTTP since you're catching "User-Agent" and "Accept". If I'm correct, there's no header with the information you're looking for, as you can check on https://en.wikipedia.org/wiki/List_of_HTTP_header_fields.

Reading HttpURLConnection

I've been trying to figure out how to read a HttpURLConnection. According to this example: http://www.vogella.com/tutorials/AndroidNetworking/article.html , the following code should work. However, readStream never fires, and I'm not logging any lines.
I do get that the InputStream is passed through the buffer and all, but for me the logic breaks down in the readStream method, and then mostly the empty string 'line' and the while statement. What exactly is happening there / should happen there, and how would I be able to fix it? Also, why do I have to create the url in the Try statement? It gives back a Unhandled Exception; java.net.MalformedURLException.
Thanks in advance!
static String SendURL(){
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream (con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return ("Done");
}
static void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.i("Tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
There are a bunch of things wrong with the code I posted in the question. Here is a working example:
public class GooglePlaces extends AsyncTask {
public InputStream inputStream;
public GooglePlaces(Context context) {
String url = "https://www.google.com";
try {
HttpRequest httpRequest = requestFactory.buildGetRequest(new GenericUrl(url));
HttpResponse httpResponse = httpRequest.execute();
inputStream = httpResponse.getContent();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
try {
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
Log.i("GooglePlacesTag", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It appears you are not connecting your HTTPUrlClient try con.connect()

How to display html page when server requesting?

I have a problem with showing html page form localhost. Here is my method but I just get System.out.println("IN !") in loop (eclipse console). When I'm putting http://localhost:1600/myWebPage.html adress in my browser nothing happened. I'm wondering how to show web page or just some text in browser after typing http://localhost:1600/myWebPage.html. Is this path correct ?
public class ServerWWW {
//localhost:1600/
public static void main(String[] args) {
int portServerWww = 1600;
ServerSocket ss = null;
try {
ss = new ServerSocket(portServerWww);
System.out.println("Server WWW waiting .....");
while(true) {
Socket s = ss.accept(); // block
new ServiceWWW (s).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class ServiceWWW extends Thread {
private Socket s = null;
private int counter;
public ObslugaWWW(Socket s) {
this.s = s;
}
public void run(){
try {
System.out.println("IN !"); //Loop
URL url = new URL("http://localhost:1600/myWebPage.html");
HttpURLConnection yc = (HttpURLConnection)url.openConnection();
yc.setRequestMethod("GET");
yc.setDoOutput(true);
yc.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(yc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "OK";
while ((line = rd.readLine()) != null){
sb.append(line + '\n');
}
System.out.println(sb.toString());
yc.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories