Open Source Java HTTP Codecs - java

I am writing a web server from the scratch. There I need a Http codec which can decode a string request (buffer) to an Http object and encode http object into Sting (buffer).
I found three Codecs,
Apache Codecs (can't use this because this is tightly coupled with their server coding structure)
Netty Codes (can't use this because this is tightly coupled with their server coding structure)
JDrupes Codecs (Has some concurrency issues)
But non of these can be used for my purpose. Are there any other Codecs I can use?

class SimpleHttpsServer implements Runnable {
Thread process = new Thread(this);
private static int port = 3030;
private String returnMessage;
private ServerSocket ssocket;
/************************************************************************************/
SimpleHttpsServer() {
try {
ssocket = new ServerSocket(port);
System.out.println("port " + port + " Opend");
process.start();
} catch (IOException e) {
System.out.println("port " + port + " not opened due to " + e);
System.exit(1);
}
}
/**********************************************************************************/
public void run() {
if (ssocket == null)
return;
while (true) {
Socket csocket = null;
try {
csocket = ssocket.accept();
System.out.println("New Connection accepted");
} catch (IOException e) {
System.out.println("Accept failed: " + port + ", " + e);
System.exit(1);
}
try {
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(csocket.getInputStream()));
PrintStream printStream = new PrintStream(new BufferedOutputStream(csocket.getOutputStream(), 1024),
false);
this.returnMessage = "";
InputStream inputStream = csocket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// code to read and print headers
String headerLine = null;
while ((headerLine = bufferedReader.readLine()).length() != 0) {
System.out.println(headerLine);
}
// code to read the post payload data
StringBuilder payload = new StringBuilder();
while (bufferedReader.ready()) {
payload.append((char) bufferedReader.read());
}
System.out.println("payload.toString().length() " + payload.toString().length());
if (payload.toString().length() != 1 || payload.toString().length() != 0) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(payload.toString());
// Handle here your string data and make responce
// returnMessage this can store your responce message
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + this.returnMessage;
printStream.write(httpResponse.getBytes("UTF-8"));
printStream.flush();
}else {
/*String httpResponse = "HTTP/1.1 200 OK\r\n\r\n";
outStream.write(httpResponse.getBytes("UTF-8"));
outStream.flush();*/
}
printStream.close();
dataInputStream.close();
// csocket.close();
System.out.println("client disconnected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/************************************************************************************/
public static void main(String[] args) {
new SimpleHttpsServer();
}
}
may be this one is help you

Related

I am not receiving response data from the client to the Java Spring Boot server

I'm new to sockets in java.
I would like to know why I am not able to receive the data from the client to the server.
after making the connection, I can send data to the client, but with "client.observable.subscribe" I can not see the return data
Server code:
#GetMapping("/desktop/{client}")
public DeferredResult<String> getScreenshot(#PathVariable("client") String clientName) {
DeferredResult<String> result = new DeferredResult<>();
Client client = ClientListenerService.getClient(clientName);
if (client == null) {
result.setResult(new JSONObject().put("error", "Requested client was not found").toString());
return result;
}
Long requestID = client.getRequestID();
JSONObject request = new JSONObject();
request.put("id", requestID);
request.put("type", RequestType.GET_SCREENSHOT.getValue());
try {
PrintWriter out = new PrintWriter(client.socket.getOutputStream(), true);
out.println(request.toString());
} catch (IOException ex) {
result.setResult(new JSONObject().put("error", "Failed to write to the socket, exception: " + ex).toString());
return result;
}
Runnable task = () -> {
client.observable.subscribe((response) -> {
JSONObject responseJson = new JSONObject(response);
if (responseJson.has("id") && responseJson.getLong("id") == requestID) {
result.setResult(response);
Thread.currentThread().interrupt();
}
}, (error) -> {});
};
Thread thread = new Thread(task);
thread.start();
return result;
}
Client code:
public static void main(String[] args) throws IOException {
Socket socketClient = null;
BufferedReader in = null;
PrintWriter out = null;
try {
socketClient = new Socket("localhost", 2222);
in = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream())),true);
} catch (IOException e) {
System.err.println("Cannot set I/O channels for connection");
System.exit(-1);
}
try {
String line;
line = in.readLine();
System.out.println("Response server: " + line);
out.println(line); // Send to server
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
out.close();
in.close();
socketClient.close();
}
I hope your help community, thank you

How to fix the error when passing JSON via Socket using Postman

My team is trying to build the application that detects the movement of the object and sending those information(JSON) to server(backend using java). I have tried to get JSON data via socket, but it shows this kind of error. I'm using postman to send JSON to test. Another question is using tomcat to get and post data from browser is better than using socket in this scenario?
public class ThreadedEchoServer {
static final int PORT = 5000;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
System.out.println("Client connect...");
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
new EchoThread(socket).start();
}
}
}
public class EchoThread extends Thread {
protected Socket socket;
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
}
public void run() {
InputStream inp = null;
BufferedReader brinp = null;
PrintWriter out = null;
try {
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
// out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
return;
}
String line;
while (true) {
try {
line = brinp.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")) {
socket.close();
return;
} else {
JSONObject json = new JSONObject(line);
System.out.println("Client: " + json.toString());
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
Here is json that I used Postman to post request
{
"id": 963,
"result": "United States",
"cook": 30
}
But I got this error
Client connect...
Exception in thread "Thread-0" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:505)
at org.json.JSONObject.<init>(JSONObject.java:215)
at org.json.JSONObject.<init>(JSONObject.java:399)
at EchoThread.run(EchoThread.java:34)

What is run() function doing in ProxyThread class if is not called anywhere?

This is the class containing the main() method:
public class MultithreadedProxyServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
int port = 10000; //default
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
//ignore me
System.out.println("gnore");
}
try {
serverSocket = new ServerSocket(port);
System.out.println("Started on: " + port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + args[0]);
System.exit(-1);
}
while (listening) {
new ProxyThread(serverSocket.accept()).start();
}
serverSocket.close();
}
}
And this is the ProxyThread class:
public class ProxyThread extends Thread {
private Socket socket = null;
private static final int BUFFER_SIZE = 32768;
public ProxyThread(Socket socket) {
super("ProxyThread");
this.socket = socket; //initialzed my parent before you initalize me
}
public void run() {
//get input from user
//send request to server
//get response from server
//send response to user
System.out.println("run");
try {
DataOutputStream out =
new DataOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String inputLine, outputLine;
int cnt = 0;
String urlToCall = "";
///////////////////////////////////
//begin get request from client
while ((inputLine = in.readLine()) != null) {
try {
StringTokenizer tok = new StringTokenizer(inputLine);
tok.nextToken();
} catch (Exception e) {
System.out.println("break");
break;
}
//parse the first line of the request to find the url
if (cnt == 0) {
String[] tokens = inputLine.split(" ");
urlToCall = tokens[1];
//can redirect this to output log
System.out.println("Request for : " + urlToCall);
}
cnt++;
}
//end get request from client
///////////////////////////////////
BufferedReader rd = null;
try {
//System.out.println("sending request
//to real server for url: "
// + urlToCall);
///////////////////////////////////
//begin send request to server, get response from server
URL url = new URL(urlToCall);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
//not doing HTTP posts
conn.setDoOutput(false);
//System.out.println("Type is: "
//+ conn.getContentType());
//System.out.println("content length: "
//+ conn.getContentLength());
//System.out.println("allowed user interaction: "
//+ conn.getAllowUserInteraction());
//System.out.println("content encoding: "
//+ conn.getContentEncoding());
//System.out.println("content type: "
//+ conn.getContentType());
// Get the response
InputStream is = null;
HttpURLConnection huc = (HttpURLConnection)conn;
if (conn.getContentLength() > 0) {
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
}
//end send request to server, get response from server
///////////////////////////////////
///////////////////////////////////
//begin send response to client
byte by[] = new byte[ BUFFER_SIZE ];
int index = is.read( by, 0, BUFFER_SIZE );
while ( index != -1 )
{
out.write( by, 0, index );
index = is.read( by, 0, BUFFER_SIZE );
}
out.flush();
//end send response to client
///////////////////////////////////
} catch (Exception e) {
//can redirect this to error log
System.err.println("Encountered exception: " + e);
//encountered error - just send nothing back, so
//processing can continue
out.writeBytes("");
}
//close out all resources
if (rd != null) {
rd.close();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have copy-pasted the above code from the internet, however I am having difficulties running it.
To answer the question from the post title, the run() method from ProxyThread class is called by JVM, after the thread has been started new ProxyThread(serverSocket.accept()).start(); and it usually contains the actual work that a thread should performed (in this case, it handles whatever the server socket receives and it accepts a connection from a client).
The moment when JVM calls run() method cannot be controlled by the programmer, but is after the thread has been started.
run() method is never called explicitly by the programmer.

Java: TCP socket connection. Client receiving null/readline() returns null

I am new to java TCP socket. I tried to implement a server and a client. So the server should check input (do something) and send string to client. The client should send string to the server and look for an input string from the server (and do something). Both should loop checking and sending all the time if something new is available.
The client can send data to the server, the server receives it an can display/process this data.
But the data from the server isn't displayed by the client. Can someone tell me why the client isn't receiving the string from the server? Any better ideas to do endless loop? There will be only one client and one server.
while true:
server out------> send String-----> in client
in<----- sent String <------ out
this is the simplified server part:
public class MainActivity extends Activity {
Socket client;
ServerSocket server;
int serverport = 54321;
String inputData = null;
BufferedReader in;
PrintWriter out;
String outputData;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(setupConnection).start();
}
private Runnable setupConnection = new Thread() {
public void run() {
try {
server = new ServerSocket(serverport);
while (true) {
client = server.accept();
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
inputData = in.readLine();
InputStream inStream = new ByteArrayInputStream(inputData.getBytes());
in.close();
if (inputData != null) {
System.out.println(TAG + "-----Incoming Message---- " + inputData);
//this is working String is shown
} }
out.write("nothing to do?");
out.flush();
out.close();
}
} catch (SocketException e) {
Log.v(TAG, "SocketException: " + e);
e.printStackTrace();
} catch (IOException e) {
Log.v(TAG, "IOException: " + e);
e.printStackTrace();
}
}
the simplified client looks like this:
public class testClass {
public static void main(String[] args) throws IOException, InterruptedException {
Socket socket = null;
String host = "127.0.0.1";
int port = 54321;
PrintWriter out = null;
BufferedReader in = null;
while (true) {
try {
socket = new Socket(host, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println(TAG + "Error: " + e);
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.out.println(TAG + "Error: " + e);
System.err.println("Couldn't get I/O for " + "the connection to: localhost.");
System.exit(1);
}
out.println("Hello, is it me you're looking for...");
out.flush();
String input = in.readLine();
System.out.println("Input: " + input);
in.close();
out.close();
}
}
}
If readLine() returns null,the peer has closed the connection, and you must do likewise. And stop reading.
if you want implement this code in android , you faces many problems:
you can find the solution in this link:
Post JSON in android
in the following code may be fix this problem:
HttpPost post = new HttpPost("http://xxxxxx");
DefaultHttpClient httpClient = new DefaultHttpClient();
post.setEntity(new ByteArrayEntity(json.toString().getBytes()));
HttpResponse response = httpClient.execute(post);
return EntityUtils.toString(response.getEntity());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println(">>>>>>>" + e.getMessage());
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println(">>>>>>>" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.println(">>>>>>>" + e.getMessage());
}

How to redirect to locally stored index.html file when localhost:<port> is called from a browser

I am creating a socket server in android. I have a directory in my local storage in which there is index.html and all other resources needed. I want that when i start the socket server and then call localhost: from my mobile's browser then it redirects to the index.html.
My socket is running. the logs are printing. the issue is i don't know how to redirect to index.html.
Thanks in advance.
Below is my code:
public class Server {
MainActivity activity;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
public Server(MainActivity activity) {
this.activity = activity;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("SocketServerThread.run i am running");
}
});
SocketServerReplyThread socketServerReplyThread =
new SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Server, you are #" + cnt;
final String OUTPUT = "https://www.google.com";
final String OUTPUT_HEADERS = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html; charset=UTF-8\r\n" +
"date: Fri, 25 Oct 2019 04:58:29 GMT"+
"Content-Length: ";
final String OUTPUT_END_OF_HEADERS = "\r\n\r\n";
try {
outputStream = hostThreadSocket.getOutputStream();
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(
new BufferedOutputStream(outputStream),"UTF-8" ));
out.write(OUTPUT_HEADERS + OUTPUT.length() + OUTPUT_END_OF_HEADERS + OUTPUT);
out.flush();
out.close();
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("Here is another message for you " + message);
}
});
}
}
public String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress
.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "Server running at : "
+ inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
Finally I got the solution to my problem here it is
static final File WEB_ROOT = new File("<your files path>");
static final String DEFAULT_FILE = "index.html";
static final String FILE_NOT_FOUND = "404.html";
static final String METHOD_NOT_SUPPORTED = "not_supported.html";
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
connect = socket;
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("SocketServerThread.run i am running");
}
});
JavaHTTPServer.SocketServerReplyThread socketServerReplyThread =
new JavaHTTPServer.SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {// we manage our particular client connection
BufferedReader in = null;
PrintWriter out = null;
BufferedOutputStream dataOut = null;
String fileRequested = null;
try {
// we read characters from the client via input stream on the socket
in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
// we get character output stream to client (for headers)
out = new PrintWriter(connect.getOutputStream());
// get binary output stream to client (for requested data)
dataOut = new BufferedOutputStream(connect.getOutputStream());
// get first line of the request from the client
String input = in.readLine();
System.out.println("SocketServerReplyThread.run input " + input);
// we parse the request with a string tokenizer
if (input == null)
return;
StringTokenizer parse = new StringTokenizer(input);
System.out.println("SocketServerReplyThread.run parse " + parse);
String method = parse.nextToken().toUpperCase(); // we get the HTTP method of the client
System.out.println("SocketServerReplyThread.run method " + method);
// we get file requested
fileRequested = parse.nextToken().toLowerCase();
if (fileRequested.contains("?"))
fileRequested = fileRequested.split("\\?")[0];
System.out.println("SocketServerReplyThread.run fileRequested " + fileRequested);
// we support only GET and HEAD methods, we check
if (!method.equals("GET") && !method.equals("HEAD")) {
if (verbose) {
System.out.println("501 Not Implemented : " + method + " method.");
}
// we return the not supported file to the client
File file = new File(WEB_ROOT, METHOD_NOT_SUPPORTED);
int fileLength = (int) file.length();
String contentMimeType = "text/html";
//read content to return to client
byte[] fileData = readFileData(file, fileLength);
// we send HTTP Headers with data to client
out.println("HTTP/1.1 501 Not Implemented");
out.println("Server: Java HTTP Server from SSaurel : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + contentMimeType);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
// file
dataOut.write(fileData, 0, fileLength);
dataOut.flush();
} else {
// GET or HEAD method
if (fileRequested.endsWith("/")) {
fileRequested += DEFAULT_FILE;
}
File file = new File(WEB_ROOT, fileRequested);
int fileLength = (int) file.length();
String content = getContentType(fileRequested);
if (method.equals("GET")) { // GET method so we return content
byte[] fileData = readFileData(file, fileLength);
// send HTTP Headers
out.println("HTTP/1.1 200 OK");
out.println("Server: Java HTTP Server from SSaurel : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + content);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
dataOut.write(fileData, 0, fileLength);
dataOut.flush();
}
if (verbose) {
System.out.println("File " + fileRequested + " of type " + content + " returned");
}
}
} catch (FileNotFoundException fnfe) {
try {
fileNotFound(out, dataOut, fileRequested);
} catch (IOException ioe) {
ioe.printStackTrace();
System.err.println("Error with file not found exception : " + ioe.getMessage());
}
} catch (IOException ioe) {
System.err.println("Server error : " + ioe);
} finally {
try {
in.close();
out.close();
dataOut.close();
connect.close(); // we close socket connection
} catch (Exception e) {
System.err.println("Error closing stream : " + e.getMessage());
}
if (verbose) {
System.out.println("Connection closed.\n");
}
}
}
}
private byte[] readFileData(File file, int fileLength) throws IOException {
FileInputStream fileIn = null;
byte[] fileData = new byte[fileLength];
try {
fileIn = new FileInputStream(file);
fileIn.read(fileData);
} finally {
if (fileIn != null)
fileIn.close();
}
return fileData;
}
// return supported MIME Types
private String getContentType(String fileRequested) {
if (fileRequested.endsWith(".htm") || fileRequested.endsWith(".html"))
return "text/html";
else
return "text/plain";
}
private void fileNotFound(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
File file = new File(WEB_ROOT, FILE_NOT_FOUND);
int fileLength = (int) file.length();
String content = "text/html";
byte[] fileData = readFileData(file, fileLength);
out.println("HTTP/1.1 404 File Not Found");
out.println("Server: Java HTTP Server from SSaurel : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + content);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
dataOut.write(fileData, 0, fileLength);
dataOut.flush();
if (verbose) {
System.out.println("File " + fileRequested + " not found");
}
}

Categories

Resources