I'm creating one java http server, that usues html5 to play music.
The problem is that when I connect to the server over my browser ( chromium, firefox) it does not play the audio. But if I select to my browser show me the font code and I copy the font code and paste it on a file .html and I open this file with browser its works. What is my problem?
This is my java server
package br.ufla.sd.trabfinal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerHttp extends Thread {
private Socket clientSocket;
private static ServerSocket serverSocket;
private static int portNumber = 8088;
private PrintWriter out;
/**
* WebServer constructor.
*/
private ServerHttp(Socket clientSoc) {
clientSocket = clientSoc;
start();
}
public static void main(String args[]) {
serverSocket = null;
try {
serverSocket = new ServerSocket(portNumber);
System.out.println("Connection Socket Created");
try {
while (true) {
System.out.println("Waiting for Connection");
new ServerHttp(serverSocket.accept());
}
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
} catch (IOException e) {
System.err.println("Could not listen on port:" + portNumber);
System.exit(1);
} finally {
try {
serverSocket.close();
} catch (IOException e) {
System.err.println("Could not close port: " + portNumber);
System.exit(1);
}
}
}
public void run() {
System.out.println("New Communication, Thread " + this.getId()
+ " Started");
try {
// remote is now the connected socket
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream());
// read the data sent. We basically ignore it,
// stop reading once a blank line is hit. This
// blank line signals the end of the client HTTP
// headers.
String str = ".";
while (!str.equals(""))
str = in.readLine();
// Send the response
// Send the headers
out.println("HTTP/1.1 200 OK");
//out.println("Content-Type: text/html");
//out.println("Server: Bot");
// this blank line signals the end of the headers
out.println("");
// Send the HTML page
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\">");
out.println("<title> Músicas</title>");
out.println("</head>");
out.println("<body>");
out.println("<H1>Welcome</H1>");
out.println("<audio controls>");
out.println("<source src=\"/****/Horse.wav\" type=\"audio/wav\">");
out.println("Your browser does not support the audio element.");
out.println("</audio>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
And another thing, if I change the file location to a online sound like this site : Site sound it works... Is someone know what is my problem?
Thanks!!
The problem is that you are just giving a path to the audio source. Think what will happen once this page loads on a browser and the user clicks to start the audio file.
Your browser will send a request again to the server to fetch the audio file. At this point in time, your server should accept the request and send the audio file back to the browser as an output stream.
The external link works because the file is present at the external link.
For your browser, the file is not present as your server doesn't seem to return any file for the request that the browser is making.
To confirm this you can check your browser's console. You will get a 404 for the audio file.
Related
I have a Java App that creates a local HTTP Webserver on Port 8080. Is there any possible Way how I can use/ install Php on it? I searched on google about this but couldnt find any help..... Any Help is appreciated!
My Code so far:
package minet;
import java.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
public class main {
private static ServerSocket serverSocket;
public static void main(String[] args) throws IOException {
JFrame ip = new JFrame();
JTextField field = new JTextField();
field.setText("http://" + getIP() + ":8080");
field.setEditable(false);
field.setBounds(10, 10, 380, 110);
ip.add(field);
JButton shutdown = new JButton("Shutdown Minet");
shutdown.setBounds(30, 120, 340, 50);
ip.add(shutdown);
ip.setLocationRelativeTo(null);
ip.setSize(400, 200);
ip.setLayout(null);
ip.setVisible(true);
shutdown.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Shutting down Minet...");
field.setText("Shutting down Minet...");
setTimeout(() -> System.exit(0), 1000);
}
});
serverSocket = new ServerSocket(8080); // Start, listen on port 8080
while (true) {
try {
Socket s = serverSocket.accept(); // Wait for a client to connect
new ClientHandler(s); // Handle the client in a separate thread
} catch (Exception x) {
System.out.println(x);
}
}
}
public static void setTimeout(Runnable runnable, int delay) {
new Thread(() -> {
try {
Thread.sleep(delay);
runnable.run();
} catch (Exception e) {
System.err.println(e);
}
}).start();
}
private static String getIP() {
// This try will give the Public IP Address of the Host.
try {
URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ipAddress = new String();
ipAddress = (in.readLine()).trim();
/*
* IF not connected to internet, then the above code will return one empty
* String, we can check it's length and if length is not greater than zero, then
* we can go for LAN IP or Local IP or PRIVATE IP
*/
if (!(ipAddress.length() > 0)) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
} catch (Exception ex) {
return "ERROR";
}
}
System.out.println("IP Address is : " + ipAddress);
return (ipAddress);
} catch (Exception e) {
// This try will give the Private IP of the Host.
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
} catch (Exception ex) {
return "ERROR";
}
}
}
}
// A ClientHandler reads an HTTP request and responds
class ClientHandler extends Thread {
private Socket socket; // The accepted socket from the Webserver
// Start the thread in the constructor
public ClientHandler(Socket s) {
socket = s;
start();
}
// Read the HTTP request, respond, and close the connection
public void run() {
try {
// Open connections to the socket
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
// Read filename from first input line "GET /filename.html ..."
// or if not in this format, treat as a file not found.
String s = in.readLine();
System.out.println(s); // Log the request
// Attempt to serve the file. Catch FileNotFoundException and
// return an HTTP error "404 Not Found". Treat invalid requests
// the same way.
String filename = "";
StringTokenizer st = new StringTokenizer(s);
try {
// Parse the filename from the GET command
if (st.hasMoreElements() && st.nextToken().equalsIgnoreCase("GET") && st.hasMoreElements())
filename = st.nextToken();
else
throw new FileNotFoundException(); // Bad request
// Append trailing "/" with "index.html"
if (filename.endsWith("/"))
filename += "index.html";
// Remove leading / from filename
while (filename.indexOf("/") == 0)
filename = filename.substring(1);
// Replace "/" with "\" in path for PC-based servers
filename = filename.replace('/', File.separator.charAt(0));
// Check for illegal characters to prevent access to superdirectories
if (filename.indexOf("..") >= 0 || filename.indexOf(':') >= 0 || filename.indexOf('|') >= 0)
throw new FileNotFoundException();
// If a directory is requested and the trailing / is missing,
// send the client an HTTP request to append it. (This is
// necessary for relative links to work correctly in the client).
if (new File(filename).isDirectory()) {
filename = filename.replace('\\', '/');
out.print("HTTP/1.0 301 Moved Permanently\r\n" + "Location: /" + filename + "/\r\n\r\n");
out.close();
return;
}
// Open the file (may throw FileNotFoundException)
InputStream f = new FileInputStream(filename);
// Determine the MIME type and print HTTP header
String mimeType = "text/plain";
if (filename.endsWith(".html") || filename.endsWith(".htm"))
mimeType = "text/html";
else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg"))
mimeType = "image/jpeg";
else if (filename.endsWith(".gif"))
mimeType = "image/gif";
else if (filename.endsWith(".class"))
mimeType = "application/octet-stream";
out.print("HTTP/1.0 200 OK\r\n" + "Content-type: " + mimeType + "\r\n\r\n");
// Send file contents to client, then close the connection
byte[] a = new byte[4096];
int n;
while ((n = f.read(a)) > 0)
out.write(a, 0, n);
out.close();
} catch (FileNotFoundException x) {
out.println("HTTP/1.0 404 Not Found\r\n" + "Content-type: text/html\r\n\r\n"
+ "<html><head></head><body>" + filename + " not found</body></html>\n");
out.close();
}
} catch (IOException x) {
System.out.println(x);
}
}
}
(Stackoverflow doesnt likes that many code... Thats why i have this external Link...)
From your question I understood that you used to use PHP as a web programing language. And you want to make an application in Java that shows some pages from PHP Web Server.
For this I think you need to include Built-in web server in your application. You just need to download it, uncompress it in your application path or wherever you want. You can find an INSTALL file in the directory. Install it as it shown, then start web server by:
$ cd path/to/built-in/php/web/server
$ php -S localhost:8000
Executing cmd commands is shown in this post. You may change port number as you want.
Another variant is you will need to include compressed Apache and PHP in your application installation package, then uncompress it, and edit config files programmatically, and after your application will be installed on some computer.
For showing pages from the PHP Web Server you just need to use WebView. An example of how to use it in Swing is shown here or you may use JavaFX directly without Swing if you want, because WebView is a part of JavaFX.
I cannot determine the exact problem you are facing. But, by the question, it seems that you wan to install a PHP server alongside your JAVA server.
This can be done easily, just select a different port number, while installing PHP. Any PHP server selects port 80 by default, so this in itself solves your problem. Just install any PHP server, it can be accessed via http://localhost, whereas your java server can be accessed via http://localhost:8080.
There has been a similar discussion here. Please check it out.
I'm trying write my individual HTTP Server and I need a help .
What is the method of ServerSocket or Socket class can to invoke on the URL and brining it into a code.
For example, if I write following link <b>http://localhost:8080/coupon/add?name=coupon name</b> in browser, I would be want to get this link into my code.
Maybe who know how can I do this?
my simple code:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class HTTPServer {
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks
All your code does right now is set up a TCP server.
HTTP is a Layer 7 protocol.
Once you accept the connection from the client, HTTP can be used for communication over that TCP socket.
You'd have to parse the HTTP request that the client sends, and from that, you'd know the URL.
In your case, you said:
I write following link http://localhost:8080/coupon/add?name=coupon name in browser
Your browser will send an HTTP request like the following example:
GET /coupon/add?name=coupon+name HTTP/1.0
Host: localhost:8080
In reality, there will be more HTTP headers there, as well as a trailing \r\n, but for our sake, let's keep it simple.
Note that special characters like space are URL-encoded, however space is also encoded as + in the query string - it could be either + or %20 depending on the client.
Hopefully it's reasonably clear to you from this explanation how you get the URL from this HTTP request.
The only missing part from the actual full link is the http:// part. The distinction between HTTP and HTTPS is not part of the HTTP protocol - it's above the socket layer but below the HTTP protocol layer. If you had SSL sockets, you'd know that on the server side, and determine based on whether it was an SSL socket or a "plain" socket, whether it was http or https.
Hope that helps.
I improved for testing the startServer method for getting information.
I'm trying to include the data that comes from URL from any browsers to URI or URL class of JAVA.
This impossible ? Maybe who know how can I do this ?
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("SERVER SOCKET TESTS:");
System.out.println("getChannel: " + serverSocket.getChannel());
System.out.println("getInetAddress: " + serverSocket.getInetAddress());
System.out.println("getLocalPort: " + serverSocket.getLocalPort());
System.out.println("getLocalSocketAddress: " + serverSocket.getLocalSocketAddress());
System.out.println();
System.out.println("CLIENT SOCKET TESTS:");
System.out.println("getChannel: " + socket.getChannel());
System.out.println("getLocalAddress: " + socket.getLocalAddress());
System.out.println("getLocalPort: " + socket.getLocalPort());
System.out.println("getLocalSocketAddress: " + socket.getLocalSocketAddress());
System.out.println("getRemoteSocketAddress: " + socket.getRemoteSocketAddress());
System.out.println("getInetAddress: " + socket.getInetAddress());
System.out.println("getInputStream: " + socket.getInputStream());
System.out.println("getOutputStream: " + socket.getOutputStream());
System.out.println();
System.out.println("URI - GET INFORMATION:");
URI uri = new URI("httpscheme://world.hello.com/thismy?parameter=value");
System.out.println(uri.getHost());
System.out.println(uri.getPath());
System.out.println(uri.getQuery());
System.out.println(uri.getScheme());
}
} catch (Exception e) {
System.out.println("error");
}
}
little test:
when I run code and after that open the browser and I write in my browser, for example: http://localhost:8080 I get information, but I don't understand following:
why the serverSocket object in getInetAddress method (serverSocket.getInetAddress) have an IP4 and it 0.0.0.0 (why not a standard local ip that defined on my computer) and the socket object of getInetAddress method (socket.getInetAddress) have an IP6 and it 0:0:0:0:0:0:0:1 . How can I get a standard host name localhost how to get the URI class (with chunks of data of link)?
The port is gated nice: 8080.
The problem for getting URL path , solved.
package pk6HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Morris on 08/10/16.
*/
public class HTTPServer {
private static String headerData;
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
boolean isClosed = false;
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
try {
try (InputStream raw = socket.getInputStream()) { // ARM
System.out.println("=================BEFORE STARTING READING HEADER =======================");
System.out.println("Collecting data to string array...");
headerData = getHeaderToArray(raw);
//
System.out.println("+++++++++++++++++ AFTER ENDING READING HEADER +++++++++++++++++++++++");
System.out.println("Hello World");
}
} catch (MalformedURLException ex) {
System.err.println(socket.getLocalAddress() + " is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
} catch (Exception ex) {
System.out.println("error# " + ex.getMessage());
}
}
public static String getHeaderToArray(InputStream inputStream) {
String headerTempData = "";
// chain the InputStream to a Reader
Reader reader = new InputStreamReader(inputStream);
try {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
headerTempData += (char) c;
if (headerTempData.contains("\r\n\r\n"))
break;
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
headerData = headerTempData;
return headerTempData;
}
}
I am having trouble using code that I found to log into www.messenger.com. It seems like I am not able to write out form parameters because I do not have the right form names. I am having trouble finding the form name of the button and what to set it equal to. My end goal, is to get the html code after I log in.
Source: http://www.dreamincode.net/forums/blog/114/entry-2715-login-to-a-website-from-java/
import java.net.*;
import java.io.*;
private static URL URLObj;
private static URLConnection connect;
public static void main(String[] args) {
try {
// Establish a URL and open a connection to it. Set it to output mode.
URLObj = new URL("http://www.messenger.com/#");
connect = URLObj.openConnection();
connect.setDoOutput(true);
}
catch (MalformedURLException ex) {
System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
System.exit(1);
}
catch (Exception ex) {
System.out.println("An exception occurred. " + ex.getMessage());
System.exit(1);
}
try {
// Create a buffered writer to the URLConnection's output stream and write our forms parameters.
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));
writer.write("email=MyEmail&pass=MyPassword&submit=Sign In");
//writer.close();
// Now establish a buffered reader to read the URLConnection's input stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String lineRead = "";
// Read all available lines of data from the URL and print them to screen.
while ((lineRead = reader.readLine()) != null) {
System.out.println(lineRead);
}
reader.close();
}
catch (Exception ex) {
System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
}
}
This are the post parameters, that are send by a browser, when you click login:
default_persistent=0
email=user
initial_request_id=A2NPA_SLbM3wAkFRM_Y0fLx
lgndim=eyJ3IjoxOTIwLCJoIjoxMjAwLCJhdyI6MTkyMCwiYWgiOjExNjAsImMiOjI0fQ==
lgnjs=n
lgnrnd=125813_Br9w
login=1
lsd=AVrsF9i0
pass=pass
timezone=-120
Maybe you need some of these to get a successfull login.
You can find these as hidden parameters in the form with the id "login_form".
I can't understand why the code below doesn't work. The client sends a message to the server, and the server prints the message to standard output.
Code for the server:
import java.net.*;
import java.io.*;
import java.math.BigInteger;
public class server
{
public static void main(String args[])
{
try
{
ServerSocket server = new ServerSocket(8080);
while (true)
{
// initializations
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter out = new PrintWriter(connection.getOutputStream());
// listen for client message
String message = in.readLine();
// print raw message from client
System.out.println(message);
// close resources
if (out != null)
out.close();
if (in != null)
in.close();
if (connection != null)
connection.close();
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
System.exit(1);
}
}
}
Code for the client:
import java.net.*;
import java.io.*;
import java.math.BigInteger;
public class client
{
public static void main(String args[])
{
try
{
// initializations
Socket connection = new Socket("localhost", 8080);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter out = new PrintWriter(connection.getOutputStream());
// send message to server
out.println("Hello, world!");
// close resources
if (in != null)
in.close();
if (out != null)
out.close();
if (connection != null)
connection.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
System.exit(1);
}
}
}
Any insights? Thanks!
What you should be doing to figure out this type of problem, is to isolate where the problem comes from. Is it the Server portion, or the client portion? An easy test for the server is to start it up, then telnet to that port (ex. "telnet 127.0.0.1 8080") type in something and see if it is outputing. (btw, your server code works fine).
Doing this would allow you to focus on your client code. As Affe stated, you simply didn't flush out the input stream. Learning methodologies for troubleshooting code is at least as important as learning to write code.
Also as an aside, by convention, Java classes start with a capital letter, so it should be "Server" and "Client"
That default PrintWriter does not autoflush. (and doesnot flush on close as abstract Writer deceptively may lead you to believe. Either do:
PrintWriter out = new PrintWriter(connection.getOutputStream(), true);
or else
out.println("Hello, world!");
out.flush();
Add a flush after you write to the stream in your client :
// send message to server
out.println("Hello, world!");
out.flush();
Also Make sure the server socket is not blocked by firewall
I'm trying to create a simple Flash chat application for educational purposes, but I'm stuck trying to send a policy file from my Java server to the Flash app (after several hours of googling with little luck).
The policy file request reaches the server that sends a harcoded policy xml back to the app, but the Flash app doesn't seem to react to it at all until it gives me a security sandbox error.
I'm loading the policy file using the following code in the client:
Security.loadPolicyFile("xmlsocket://myhostname:" + PORT);
The server recognizes the request as "<policy-file-request/>" and responds by sending the following xml string to the client:
public static final String POLICY_XML =
"<?xml version=\"1.0\"?>"
+ "<cross-domain-policy>"
+ "<allow-access-from domain=\"*\" to-ports=\"*\" />"
+ "</cross-domain-policy>";
The code used to send it looks like this:
try {
_dataOut.write(PolicyServer.POLICY_XML + (char)0x00);
_dataOut.flush();
System.out.println("Policy sent to client: " + PolicyServer.POLICY_XML);
} catch (Exception e) {
trace(e);
}
Did I mess something up with the xml or is there something else I might have overlooked?
I've seen your approach and after some time trying i wrote a working class, listening on any port you want:
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class PolicyServer {
public static final String POLICY_XML =
"<?xml version=\"1.0\"?>"
+ "<cross-domain-policy>"
+ "<allow-access-from domain=\"*\" to-ports=\"*\" />"
+ "</cross-domain-policy>";
public PolicyServer(){
ServerSocket ss = null;
try {
ss = new ServerSocket(843);
} catch (IOException e) {e.printStackTrace();}
while(true){
try {
final Socket client = ss.accept();
new Thread(new Runnable() {
#Override
public void run() {
try {
client.setSoTimeout(10000); //clean failed connections
client.getOutputStream().write(PolicyServer.POLICY_XML.getBytes());
client.getOutputStream().write(0x00); //write required endbit
client.getOutputStream().flush();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//reading two lines emties flashs buffer and magically it works!
in.readLine();
in.readLine();
} catch (IOException e) {
}
}
}).start();
} catch (Exception e) {}
}
}
}
Try add \n at the end of policy xml.