Java Socket (TCP) Client Callback Functions - java

I am writing a simple Java Socket Client that is able to connect to a socket and pass a certain request to the server. Pretty much what I am trying to do:
Java Client connects to socket sends request to server
Server processes request and sends back "starting"
Java Client waits for next progress update
Server sends "progress 10%"
Java Client receives the progress update and processes accordingly
Server sends progress update 20%... so on so forth
I do not want to constantly check if there is something in the input stream but rather have the client retrieve the data as soon as there is something pending and process it (on a background thread). I am fairly new to working with java and networking in general so I don't know much about implementing this.
Server code (python, running on a raspberry pi):
import SocketServer
from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler
import sys
import time
import socket
# We mix with ThreadingMixIn to allow several simultaneous
# clients. Otherwise, a slow client may block everyone.
class ThreadingTCPServer(ThreadingMixIn, TCPServer):
pass
# StreamRequestHandler provides us with the rfile and wfile attributes
class RequestHandler(StreamRequestHandler):
def handle(self):
print str(self.client_address) + 'connected'
data = "foo"
while data != "":
data = self.rfile.readline()
print data
try:
self.wfile.write("foo\n")
except socket.error: # Client went away, do not take that data into account
data = ""
print 'Handler Exiting'
self.request.close()
def finish(self):
print 'Client Disconnected'
if __name__ == '__main__':
PORT = 80
ThreadingTCPServer.allow_reuse_address = True
server = ThreadingTCPServer(("", PORT), RequestHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
print "\nServer Terminated"
Basically at the end of prototyping I will be implementing this into an Android app. If you were wondering I am planning on using this to run some home automation and some other things.
This is the current client code I am working with (from an example online and I modified it a little):
import java.lang.*;
import java.io.*;
import java.net.*;
public class ClientTest {
private Socket socket = null;
private BufferedReader reader = null;
private BufferedWriter writer = null;
public ClientTest(InetAddress address, int port) throws IOException {
socket = new Socket(address, port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}
public void send(String msg) throws IOException {
writer.write(msg, 0, msg.length());
writer.flush();
}
public String recv() throws IOException {
return reader.readLine();
}
public static void main(String[] args) {
try {
InetAddress host = InetAddress.getByName("192.168.1.15");
ClientTest client = new ClientTest(host, 80);
//ClientTest client2 = new ClientTest(host, 9999);
for (int i = 1; i <= 1000; i++) {
client.send("bar " + i + "\n");
String response = client.recv();
System.out.println("" + i + ": " + response);
try {
Thread.sleep(15);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//client2.send("Client2\n");
}
client.socket.close();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//client2.socket.close();
} catch (IOException e) {
System.out.println("Caught Exception: " + e.toString());
}
}
}
Instead of String response = client.recv(); I want to have this function automatically called whenever the server sends back a request and have the message processed in the background. (I think it is somewhere along the lines of a callback function)
All answers appreciated!

Related

Able to write the data successfully but not able to read the data from the server

I have two classes server and client. I am running both the server and the client on the intelliji. I am able to write the data to the Json file on the server but when it comes to reading the data, I am not able to read it. My application is not responding when I am trying to read the data. I am new to Socket Programming please help me.
Here is the code on the client side
import java.io.*;
import java.net.Socket;
public class Client {
public String readDataFromServer(Socket socket) throws IOException {
InputStreamReader inputStreamReader = new
InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
return bufferedReader.readLine();
}
public void writeDataToServer(String obj) throws IOException {
Socket socket = new Socket("localhost", 1299);
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(socket.getOutputStream());
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.write(obj);
printWriter.flush();
printWriter.close();
}
}
Here is the code on the server side
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
static void writeJson (String str) throws IOException {
FileWriter pw = null;
try {
pw = new FileWriter("MYJSON.json", true);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
pw.write(str + '\n');
pw.flush();
try {
} catch (Exception E) {
E.printStackTrace();
}
pw.close();
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1299);
Socket socket = serverSocket.accept();
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = bufferedReader.readLine();
writeJson(str);
FileReader fileReader = new FileReader("MYJSON.json");
BufferedReader buff = new BufferedReader(fileReader);
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(socket.getOutputStream());
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.write(buff.readLine());
printWriter.flush();
}
}
I have another class called display controller which is calling the method which is calling the method by passing the socket object. Here is the piece of code from this class.
Client client = new Client();
button1.setOnAction(e-> {
try {
String str;
while ((str = client.readDataFromServer(socket)) != null) {
Object obj = null;
try {
obj = jsonParser.parse(str);
What I am doing wrong here? How do I fix it?
Thank you
There's a couple of issues in your code.
The main one is in the main method of the Server class. Your server only accepts one connection. That connection writes and reads the json file and then your main method ends. If your main program ends, then the server is gone. This means that the first client that connects will work and write to the file, but any subsequent connections will not connect because there's no server accepting connections anymore. Typical servers run indefinitely by using a while loop with true as the condition.
Example Structure of a server without threads:
public class Server {
// this class represents an instance of a client connection to this server
// It's an object that keeps track of the socket created by referencing
// the connection.
private class ClientInstanceOnTheServer {
private Socket connectionToClient;
public ClientInstanceOnTheServer(Socket connectionToClient) {
this.connectionToClient = connectionToClient;
}
private void logicToServeAClient() {
// here goes the logic that serves a client
}
public void run () {
try {
logicToServeAClient();
} finally {
try {
socket.close();
} catch (IOException e) {// handle exceptions!}
}
}
}
public static void main(String [] args) {
try {
ServerSocket serverSocket = new ServerSocket(1299);
while (true) { // run indefinitely
Socket socket = serverSocket.accept(); // accept connections from clients
// keep track of the socket object as it represents a connection to a client
// the server is responsible for keeping track of its connections to clients
// Example:
ClientInstanceOnTheServer client = new ClientInstanceOnTheServer(socket);
client.run();
}
} finally {
serverSocket.close();
}
}
}
Example Structure of a server with Threads:
NOTE: The code below is not to represent a complete solution with threads, but rather an example to explain how a server works.
public class Server {
// this class represents an instance of a client connection to this server
// It's an object that keeps track of the socket created by
// the connection and it runs in a separate thread to not block
// the main method thread on this server.
private class ClientInstanceOnTheServer extends Thread {
private Socket connectionToClient;
public ClientInstanceOnTheServer(Socket connectionToClient) {
this.connectionToClient = connectionToClient;
}
private void logicToServeAClient() {
// here goes the logic that serves a client
}
public void run () {
try {
logicToServeAClient();
} finally {
try {
socket.close();
} catch (IOException e) {// handle exceptions!}
}
}
}
public static void main(String [] args) {
try {
ServerSocket serverSocket = new ServerSocket(1299);
while (true) { // run indefinitely
Socket socket = serverSocket.accept(); // accept connections from clients
// keep track of the socket object as it represents a connection to a client
// the server is responsible for keeping track of its connections to clients
// and it should use a separate thread for each client to not block the main method thread.
// Example:
ClientInstanceOnTheServer client = new ClientInstanceOnTheServer(socket);
client.start(); // this will execute the run method in ClientInstanceOnTheServer class.
}
} finally {
serverSocket.close();
}
}
}
Your server is always doing both, writing and reading the json file, regardless of what the client wants. The server should somehow allow the client to communicate what it wants to do, and then it executes only what the client asked for. If we use the skeleton code above, this logic would go in the method logicToServeAClient of the ClientInstanceOnTheServer class. The server and client use the socket object's input and output streams to communicate with each other. The server and client need to agree beforehand on which commands/operations the client needs and the server is willing to serve. In your case, it would be READ and WRITE. Then you create a contract (Protocol) between the client and server on how to send these commands to the server and how the server will respond to the client for each command.
Example of a protocol:
// client sends READ to server
// client waits for respond from server
// server read json file and send it to the client
// client sends WRITE to server
// server then waits for the client to send the string to write.
// Once it receives the string, it writes it to the json file.
All of this is achievable using the socket's input and output streams
It's important to distinguish the difference between the Client and the ClientInstanceOnTheServer classes. Client is your Client class that connects to the server and ClientInstanceOnTheServer holds the connection and also runs the server code that serves the commands requested by the Client class. In the protocol above, whenever client is mentioned, is referring to the Client class. Whenever the server is mentioned is referring to the ClientInstanceOnTheServer class.
You can find more examples on google, like: http://cs.lmu.edu/~ray/notes/javanetexamples/. However, this should set you up on a path to fix your issue.
Cheers

Java client and python server connection

i am working on an app in android studio and basiclly i need that whenever i clicked a specific button it will create a connection between the java client and python server.
I first checked when u enter the page\activity of the specific button if there is a wifi connection in the phone.
It works fine. then i tried to do this and it didnt work (Important to say that the current code make my phone and my app crash and stop)
simple server:
HOST = '192.168.1.21'
PORT = 9000
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
client_socket, client_address = server_socket.accept()
print 'Connect with ' + client_address[0]
data = client_socket.recv(1024)
print "data :"
print data
print " end"
if data == HOST+"/n":
print 'hi'
else:
i = 0
while i < 15:
print i
i += 1
client_socket.close()
server_socket.close()
if __name__ == '__main__':
main()
this is just to check a connection. it might look strange because of the host +/n in the if . i recently chenged it because i am new to java and dont know how the data is sent. but that is not the problem rn.
public void ButtonClicked(View view) {
EditText editText = findViewById(R.id.edit_text);
final String ip = editText.getText().toString();
Toast.makeText(this, ip, Toast.LENGTH_SHORT).show();
try {
InetAddress host = InetAddress.getByName(ip);
final Client client = new Client(host, 9000);
new Thread(new Runnable() {
public void run() {
try {
client.send(ip);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
client.send(ip);
}
catch (IOException e) {
System.out.println("Caught Exception: " + e.toString());
}
i read that in android studio 3.0 u need to create a thread when u send data.
the client class that u see here :
public class Client
{
private Socket socket = null;
private BufferedReader reader = null;
private BufferedWriter writer = null;
public Client(InetAddress address, int port) throws IOException
{
socket = new Socket(address, port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}
public void send(String msg) throws IOException
{
writer.write(msg, 0, msg.length());
writer.flush();
}
public String recv() throws IOException
{
return reader.readLine();
}
}
it might be just a simple thing that i dont know of but those are the codes and i cant connect to the server. i figured out that the server works fine because if im connecting from the phone to 192.168.1.21 on the net i receive the connection and it does thw little while.
ty for the help - i would like to get the simplest fixes because im new to java.(sorry if there where grammer\ spelling mistakes)
Edit- logcat for the crash
At the end of your log it says NetworkOnMainThread. In your code there is a line client.send(ip) below your seperate thread which is executed at the main thread.

How to retrieve data from a file very fast in Java

I have a situation like, I am provided with a log file that consists of Strings. What I have to do is , I need to retrieve each string from the file and pass through a Socket and when the End of the File reaches it has to go again to the beginning of the file and send again the Strings. I have written a simple code using an infinite thread that sends the strings and when the EOF comes I am closing the file and again re-opening the file using new BufferedReader object. And I am also giving a small amount of 5ms of thread sleep, but after some time my Process is entering into Pause state (Like a Dead Lock). Is there anyway to improve the speed of transfer? or else can I eliminate the Pause state.
Below is my Simple code:
public class Write extends Thread{
private static final String FileName = "Messages.txt";
private static final int port = 8080;
private final int time = 5;
ServerSocket serverSocket;
Socket writeSocket;
#Override
public void run()
{
try
{
serverSocket = new ServerSocket(port);
System.out.println("Server listening on port " + port+ " ...");
Socket writeSocket = serverSocket.accept();
System.out.println("Connected to Client : "+ writeSocket.getLocalSocketAddress());
OutputStream outStream = writeSocket.getOutputStream();
PrintWriter out = new PrintWriter(outStream, true);
BufferedReader input = new BufferedReader(new FileReader(FileName));
String str = "";
while(true)
{
str = input.readLine();
if(str==null ){
input.close();
input = new BufferedReader(new FileReader(FileName));
}
else{
System.out.println("Outgoing Message>>"+str);
out.println(str);
Thread.sleep(time);
}
}
}
catch(IOException e) {System.out.println(e); } catch (InterruptedException ex) {
Logger.getLogger(Write.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Let me give you a simple explanation. Consider the above code is in a Server code. And when I run a client machine in the same PC, I can able to send the messages at some(high) speed but after sometime, both the client and the Server are entering into a Pause state. I feel this like a Dead Lock. The client is showing like the Server is disconnected and again Connected. When I close the Client then again Server is starting. Can anyone tell me is there a way to process the strings at a very high speed?
Re the program blocking, I would suggest:
put a System.out.print("A") before out.println() and a System.out.print("B") after. If it blocks with "A" as the last message in the output, then the problem is at the client side (they're not consuming the data, causing eventually the sender to block).
If the previous situation happens, write your own simple client which just reads data from the socket and throws it away, so you can demonstrate the problem is at the other side.
Re speed, you want to remove the sleep and System.out.println.
Why not use java nio to read all lines?
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-java.nio.charset.Charset-
Or is the file too big to do this?
your code that reads the log file is just fine. no need to make it faster. see below (I commented the parts of the code that deal with the socket and the code works well at reading the log file multiple times. there is no sign of slowing down or deadlocks) :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Write extends Thread {
private static final String FileName = "/tmp/Messages.txt";
private static final int port = 8080;
private final int time = 5;
ServerSocket serverSocket;
Socket writeSocket;
public static void main(String[] args) {
Write write = new Write();
Thread thread = new Thread(new Write());
thread.start();
}
#Override
public void run() {
try {
// serverSocket = new ServerSocket(port);
// System.out.println("Server listening on port " + port + " ...");
// Socket writeSocket = serverSocket.accept();
// System.out.println("Connected to Client : " + writeSocket.getLocalSocketAddress());
//
// OutputStream outStream = writeSocket.getOutputStream();
// PrintWriter out = new PrintWriter(outStream, true);
BufferedReader input = new BufferedReader(new FileReader(FileName));
String str = "";
while (true) {
str = input.readLine();
if (str == null) {
input.close();
input = new BufferedReader(new FileReader(FileName));
} else {
System.out.println("Outgoing Message>>" + str);
//out.println(str);
Thread.sleep(time);
}
}
} catch (IOException e) {
System.out.println(e);
} catch (InterruptedException ex) {
Logger.getLogger(Write.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

How can read input from a Client in a simple HTTP Web Server in Java?

I am trying to create a simple HTTP web server in Java. I'm just taking this in baby steps so it's super simplistic. I'm trying to make it so I can read simple input from the Client and output anything from the Server when they are both connected.
After searching around on tutorials on websites, this is what I've done so far:
public class Server
{
public static void main(String[] args) throws Exception
{
boolean listening = true;
ServerSocket server = null;
int port = 2222;
try
{
System.out.println("Server binding to port " + port);
server = new ServerSocket(port);
}
catch(Exception e)
{
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Server successfully binded to port " + port);
while(listening)
{
System.out.println("Attempting to connect to client");
Socket client = server.accept();
System.out.println("Successfully connected to client");
new ServerThread(client).start() ;
}
server.close();
}
}
public class ServerThread extends Thread
{
private Socket socket = null ;
public ServerThread(Socket s)
{
this.socket = s ;
}
public void run()
{
InputStream in = socket.getInputStream() ;
OutputStream out = socket.getOutputStream() ;
byte [] message, reply;
while((in.read(message))
{
out.write(reply) ;
}
in.close() ;
out.close() ;
socket.close() ;
}
}
It binds and then hangs after attempting to connect to the client. This is because I'm not sure what you do in the while loop in the ServerThread and what you do with the message and reply variables >_< It's been a long time since I've done Java so take it easy on me!
I have only use this kind of server as a "curiosity", to learn new stuff nothing more because you are reinventing the wheel, security reasons etc... I only had to use it once because I had to communicate a server with a JSON code and no server could be installed.
This code needs more work such us creating a new thread for each request, a better RCF HTTP implementation but it works with your ordinary browser.
I hope this helps.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MiniPbxManServer extends Thread {
private final int PORT = 2222;
public static void main(String[] args) {
MiniPbxManServer gtp = new MiniPbxManServer();
gtp.start();
}
public void run() {
try {
ServerSocket server = new ServerSocket(PORT);
System.out.println("MiniServer active "+PORT);
boolean shudown = true;
while (shudown) {
Socket socket = server.accept();
InputStream is = socket.getInputStream();
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String line;
line = in.readLine();
String auxLine = line;
line = "";
// looks for post data
int postDataI = -1;
while ((line = in.readLine()) != null && (line.length() != 0)) {
System.out.println(line);
if (line.indexOf("Content-Length:") > -1) {
postDataI = new Integer(line
.substring(
line.indexOf("Content-Length:") + 16,
line.length())).intValue();
}
}
String postData = "";
for (int i = 0; i < postDataI; i++) {
int intParser = in.read();
postData += (char) intParser;
}
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html; charset=utf-8");
out.println("Server: MINISERVER");
// this blank line signals the end of the headers
out.println("");
// Send the HTML page
out.println("<H1>Welcome to the Mini PbxMan server</H1>");
out.println("<H2>GET->"+auxLine+ "</H2>");
out.println("<H2>Post->"+postData+ "</H2>");
out.println("<form name=\"input\" action=\"imback\" method=\"post\">");
out.println("Username: <input type=\"text\" name=\"user\"><input type=\"submit\" value=\"Submit\"></form>");
//if your get parameter contains shutdown it will shutdown
if(auxLine.indexOf("?shutdown")>-1){
shudown = false;
}
out.close();
socket.close();
}
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
url: localhost:2222/whatever
I think you're going the right way at a high level. The difference between what you've got and production systems is that they do their polling for input on a socket is done in a different thread so as not to halt the system while waiting for input.
In fact, one of the configuration parameters for a web server is how many clients (threads) to have up and running.
You should always flush data from the server's output stream. The client response may depend on this:
out.flush();
To check for the end of stream, you could use:
int result = 0;
while ((result = in.read(message)) != -1) {
...
Also your reply message does not appear to be initialized, you probably want to resend the client data initially:
reply = message;
The jdk has a simplistic http server included to build embedded http servers. Take a look at this link.

URL Parsing with Java server using Runnable class

How can I parse URL queries with a system like this.
For Example something like get these URL arguments in variables.
http://localhost?format=json&apikey=838439873473kjdhfkhdf
http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html
I made these files
WorkerRunnable.java
package servers;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.net.Socket;
/**
*/
public class WorkerRunnable implements Runnable{
protected Socket clientSocket = null;
protected String serverText = null;
public WorkerRunnable(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
public void run() {
try {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " +
this.serverText + " - " +
time +
"").getBytes());
output.close();
input.close();
System.out.println("Request processed: " + time);
} catch (IOException e) {
//report exception somewhere.
e.printStackTrace();
}
}
}
MultiThreadedServer.java
package servers;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class MultiThreadedServer implements Runnable{
protected int serverPort = 8080;
protected ServerSocket serverSocket = null;
protected boolean isStopped = false;
protected Thread runningThread= null;
public MultiThreadedServer(int port){
this.serverPort = port;
}
public void run(){
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException(
"Error accepting client connection", e);
}
new Thread(
new WorkerRunnable(
clientSocket, "Multithreaded Server")
).start();
}
System.out.println("Server Stopped.") ;
}
private synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stop(){
this.isStopped = true;
try {
this.serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
}
Dispatch.java
package servers;
public class Dispatch {
/**
* #param args
*/
public static void main(String[] args) {
MultiThreadedServer server = new MultiThreadedServer(9000);
new Thread(server).start();
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Stopping Server");
server.stop();
}
}
You're doing fine so far.
Read the data off of the InputStream (BufferedReader might help) one line at a time.
Read and learn the HTTP Protocol (see Request Message section here: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol).
The first line that the client sends is going to follow that format: GET /foo.html?x=y&a=b HTTP/1.1 followed by \n\n that's the Method, URL (with query parameters) and Protocol. Split that line (on the spaces...) and then break the URL up according to the specs.
Everything you need can be found in the String class for parsing the data.
You have forgotten to read what the clients sends. In http the clients opens the connection and than sends the request and waits for the server to reply.
To read the request you have two options. Use a BufferedReader or read it byte by byte.
The BufferedReader is easier. You get a String for every line and can easily split it or replace characters, or whatever ;)
Reading every byte is a little bit faster, but it will only be relevant if you need to serve a huge amount of request per seconds. Than this can really make a difference. I just put this information just so you know ;)
I have included the necessary part for reading in your WorkerRunnable.java.
This reads and prints out the whole client request.
Start your server, open your browser and type: http://127.0.0.1:9000/hello?one=1&two=2&three=3
The First line on the Console will read: GET /hello?one=1&two=2&three=3 HTTP/1.1
Before closing an OutputStream, be sure to call the flush() method. This will force any buffered bytes to be written out. If you don't do it, than there might be some bytes/characters missing and you might be spending a long time looking for the error.
try {
InputStream input = clientSocket.getInputStream();
// Reading line by line with a BufferedReader
java.io.BufferedReader in = new java.io.BufferedReader(
new java.io.InputStreamReader(input));
String line;
while ( !(line=in.readLine()).equals("") ){
System.out.println(line);
}
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " +
this.serverText + " - " +
time +
"").getBytes());
output.flush();
//Flushes this output stream and forces any buffered output bytes to be written out.
output.close();
input.close();
System.out.println("Request processed: " + time);
I don't know exactly what you are doing there. You just told us you need to parse the URL, but maybe a better way is to use the simpleframework (http://www.simpleframework.org)
It is like an embedded HTTP-Server, you can look at the tutorial. It will give you a request object, from there you can easily fetch the parameters in the url.
Technically speaking, you can, but it would leave you with implementing the http protocol on your own.
A much better option would be to use the Java Http Server from Oracle. See the following article for tips http://alistairisrael.wordpress.com/2009/09/02/functional-http-testing-with-sun-java-6-httpserver/

Categories

Resources