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();
}
}
}
Related
I am getting the error in the part where it says (final (String[] args)). It would be great if somebody knows why this error is occurring. Thanks in advance! I have included the code.
public class PartOne {
private static Object BufferedReader;
public static <String> void PartOne (final (String[] args))
{
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("words-sowpods.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
}
}
There are couple of things wrong here-
public static void PartOne (final (String[] args))
why u have making generic type as String even though is void
param is incorrect
Please find the correct implementation :
public static void PartOne(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("words-sowpods.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am using a data generator which uses ports for streaming data. I use multiple ports mfor receiving data. The software I am writing makes a new socket for each port. Every socket should make an instance of a class called 'Interpreter'.
The problem I have is the following: I am able to make multiple instances of Interpreter, but I think the data is all being parsed to only one of the instances. I think this happens because the data is 'merged' in the output.
This is the most important snipet of the code:
public class Main {
public static void main (String[] args) {
Socket socket;
ServerSocket serverSocket=null;
System.out.println("Server Listening..");
try{
serverSocket = new ServerSocket(7789);
}
catch(IOException e){
e.printStackTrace();
System.out.println("Error");
}
while(true){
try{
socket= serverSocket.accept();
Interpreter interp = new Interpreter();
ServerThread serverThr=new ServerThread(socket, interp);
serverThr.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread {
String line = null;
BufferedReader is = null;
PrintWriter os = null;
Socket s = null;
public ServerThread(Socket s, Interpreter interp) {
this.interp = interp;
this.s = s;
System.out.println("interp "+interp);
System.out.println("s: "+s);
System.out.println("poort: "+s.getPort());
}
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();
Interpreter.interpreter(line);
line = is.readLine();
}
} catch (IOException e) {
line = this.getName();
System.out.println("IO Error/ Client " + line + " terminated abruptly");
} catch (NullPointerException e) {
line = this.getName();
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");
}
} catch (IOException ie) {
System.out.println("Socket Close Error");
}
}
}
}
This is the 'important' part of Interpreter:
public class Interpreter{
static AtomicInteger nextId = new AtomicInteger();
int id = nextId.incrementAndGet();
public Interpreter(){
System.out.println("ID of demo "+id);
}
}
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.
I made a little game. Now i want to get the highscore from my Server. The code on the client:
private int getOnlineHighscore() {
int highscore = 0;
try {
socket = new Socket("localhost", 444);
input = socket.getInputStream();
System.out.println(input);
highscore = input.read();
input.close();
socket.close();
input = null;
socket = null;
} catch (Exception e) {
System.out.println("Verbindung fehlgeschlagen!");
}
System.out.println(highscore);
return highscore;
}
And on the Server:
import java.io.*;
import java.net.*;
public class ReadServer extends Thread {
private Socket socket;
public ReadServer(Socket socket) {
super();
this.socket = socket;
}
public void run() {
try {
System.out.println(socket.getInetAddress());
String result = "";
try (BufferedReader br = new BufferedReader(
new FileReader(System.getProperty("user.home") + "/AppData/Roaming/GameServer/.sg"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
System.out.println("2");
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
System.out.println("3");
result = sb.toString();
System.out.println("3.5");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("4");
socket.getOutputStream().write(Integer.parseInt(result));
System.out.println(result);
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
public static void main(String[] Args) {
Socket socket = null;
ServerSocket server = null;
try {
server = new ServerSocket(444);
while (true) {
socket = server.accept();
new ReadServer(socket).start();
}
} catch (Exception e) {
}
try {
server.close();
} catch (Exception e) {
}
}
}
If I run it, the client function returns:
-1
The server writes in the console(not important I think):
/127.0.0.1
2
3
3.5
4
How to solve the problem? I want to send an int stored on my Server to a client.
-Jakob
-1 is returned by read() to specify end of stream , make sure data to be read is being returned .
What is the highscore stored in the file? I believe the file is empty and it fails on parsing the integer but as your catch block is empty, you don't see the exception. Put printStacktrace or rethrow.
Another problem is that OutputStream sends only bytes and therefore write method sends only low 8 bits. To send int wrap the stream with DataOutputStream and DataInputStream on the client side.
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.