private final class ServerConnectThread2 extends Thread
{
private InputStreamReader _in=null;
private OutputStreamWriter _out=null;
private String _url;
private int _delay;
private String _key;
private String _connectionParameters;
OutputStream os=null;
FileConnection fconn=null;
ServerConnectThread2()
{
_key="";
}
public void run()
{
// check internet connection available
setConnectionStringParameter();
bulkUploaderFlag=true;
HttpConnection connection = null;
try
{
_url="http://xxx/bulkuploader.jsp";
_url= EncodeURL (_url) ;
_url = _url + _connectionParameters;
URLEncodedPostData _postData = new URLEncodedPostData("",false);
_postData.append("totalRecord",""+totalRecord);
int count=0;
while( count < totalRecord)
{
_postData.append("accountID"+count,"C"+(String)accountIDVector.elementAt(count));
_postData.append("deviceID"+count,(String)deviceIDVector.elementAt(count));
_postData.append("timestamp"+count,(String)timestampVector.elementAt(count));
_postData.append("statusCode"+count,(String)statusCodeVector.elementAt(count));
_postData.append("latitude"+count,(String)latitudeVector.elementAt(count));
_postData.append("longitude"+count,(String)longitudeVector.elementAt(count));
_postData.append("gpsAge"+count,(String)gpsAgeVector.elementAt(count));
_postData.append("speedKPH"+count,(String)speedKPHVector.elementAt(count));
_postData.append("heading"+count,(String)headingVector.elementAt(count));
_postData.append("altitude"+count,(String)altitudeVector.elementAt(count));
_postData.append("transportID"+count,(String)transportIDVector.elementAt(count));
//_postData.append("inputMask",""+0);
count++;
}
byte [] postDataBytes = _postData.getBytes();
// Open the connection
connection = (HttpConnection)Connector.open(_url, Connector.READ_WRITE, false);
// Set the request method as GET
connection.setRequestMethod("POST");
//connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//connection.setRequestProperty("Content-Type","application/octet-stream");
//connection.setRequestProperty("Content-Type","multipart/form-data");
String len =new String(postDataBytes);
System.out.println(len);
connection.setRequestProperty("Content-Length",""+len.length());
os= connection.openOutputStream();
os.write(postDataBytes);
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2 ]");
int rc = connection.getResponseCode();
if(rc == HttpConnection.HTTP_OK)
{
_in = new InputStreamReader(connection.openInputStream());
// Wait for an acknowledgment, in this case an '1' character, for 'Received'.
//char c = (char)_in.read();
int length=0;
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, http==OK ]\n");
StringBuffer buf = new StringBuffer();
while ((length = _in.read()) != -1) {
char c = (char)length;
buf.append(c);
if(c=='0')
{
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, c==0,not send in bulk unsucessfully ]\n");
System.out.println("DATA not send in bulk SUCCESSFULLY sct2, c==0");
break;
}
if(c=='1')
{
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, c==1, send in bulk successfully ]\n");
System.out.println("DATA send in bulk SUCCESSFULLY sct2");
String fullPath = "file:///SDCard/dataLog.txt";
try
{
fconn = (FileConnection) Connector.open(fullPath, Connector.READ_WRITE);
if (fconn.exists())
fconn.delete();
}
catch(Exception e){}
finally
{
if(fconn!=null)
fconn.close();
}
break;
}
}
}
else
{
System.out.println("DATA not send in bulk SUCCESSFULLY sct2");
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, http not ok ]\n");
}
}
catch (Exception e)
{
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, exception catch ]\n");
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() + ", "+e.getMessage()+" ] \n");
System.out.println("DATA not send in bulk SUCCESSFULLY"+e.getMessage());
}
finally
{
try
{
if(_in!=null)
_in.close();
if(_out!=null)
_out.close();
if(os!=null)
os.close();
if(connection!=null)
connection.close();
bulkUploaderFlag=false;
}
catch (IOException ioe)
{
// Do Nothing
}
return;
}
}
I think , you must call "dos.flush()" method. My code runs perfectly, postContent is string buffer and contanins 300KB string.
if (getPostContent() == null) {
httpConnection.setRequestMethod(HttpConnection.GET);
} else {
String type = "application/x-www-form-urlencoded";
byte[] bytes = postContent.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Content-Type", type);
httpConnection.setRequestProperty("Content-Length", bytes.length + "");
httpConnection.setRequestMethod(HttpConnection.POST); //setupPost method for this conn
DataOutputStream dos = new DataOutputStream(httpConnection.openOutputStream());
dos.write(bytes);
dos.flush();
dos.close();
}
Related
I have many images in a folder, and I want to upload this files, in that folder, to a php server, in java using httpurlconnection.
Until now, I made it but just with one photo, like the code I show you down.
public class SendImage {
private final String CrLf = "\r\n";
public static void main(String[] args) {
SendImage image = new SendImage();
image.httpConn();
}
private void httpConn(){
URLConnection lig = null;
OutputStream os = null;
InputStream is = null;
try{
String urlParameters = "subPasta=sandro&nomepc=Sandro-PC&printPasta=Printscreens";;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL url = new URL("http://192.168.0.105/dashboard3/uploadImg.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
System.out.println("url: "+ url);
lig = url.openConnection();
lig.setDoOutput(true);
FileInputStream imgIs = new FileInputStream(new File("C:\\Users\\Sandro\\workspace\\testeLogin\\screenshot\\2017_3_16_3_59.png"));
byte[] imgData = new byte[imgIs.available()];
imgIs.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"image.png\"" + CrLf;
message1 += "Content-Type: image/jpeg" + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--" + CrLf;
lig.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
lig.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
System.out.println("open os");
os = lig.getOutputStream();
System.out.println(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
System.out.println("write:" + index);
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
System.out.println("written:" + index);
System.out.println(message2);
os.write(message2.getBytes());
os.flush();
System.out.println("open is");
is = lig.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
System.out.println("READ");
len = is.read(data);
if (len > 0) {
System.out.println(new String(data, 0, len));
}
} while (len > 0);
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally {
System.out.println("Close connection");
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
try {
} catch (Exception e) {
}
}
}
}
But I want send all photos in that folder
if you can, show me the code in php too please.
I have posted my java proxy code below.
It works but it only gives me 1 server response instead of everything.
After the 1 response I just get client sent packets but with a size of 0.
Screenshots also attached.
Any ideas?
I've done some debugging. If I remove everything in between
typ = streamFromServer.readUnsignedShort();
siz = streamFromServer.readUnsignedShort();
siz <<= 8;
siz |= streamFromServer.readUnsignedByte();
byte[] dat = new byte[siz];
streamFromServer.readFully(dat, 0, siz);
String FullHe = DatatypeConverter.printHexBinary(dat);
System.out.println("Server sending data to Client:");
System.out.println("Type: " + typ + "");
System.out.println("Data Size: " + siz + "");
System.out.println("Full Data: " + FullHe + "");
System.out.println("\n\n");
Which is from the reading server response code it works and I get the client packets. How come it doesn't work with server packets?
Code:
import java.io.*;
import javax.xml.bind.DatatypeConverter;
import java.net.*;
public class proxy{
public static void main(String[] args) throws IOException {
//PrintStream out = new PrintStream(new FileOutputStream("log.txt"));
//System.setOut(out);
try{
String host = "gamea.clashofclans.com";
int remoteport = 9339;
ServerSocket ss = new ServerSocket(9339);
int localport = ss.getLocalPort();
ss.setReuseAddress(true);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport
+ " on port " + localport);
// And start running the server
runServer(host, remoteport, localport,ss); // never returns
System.out.println("Started proxy!");
} catch (Exception e) {
System.out.println("Failed to start proxy" +e+ "");
}
}
public static void runServer(String host, int remoteport, int localport, ServerSocket ss)
throws IOException {
final byte[] request = new byte[2048];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
System.out.println("Waiting for Client");
client = ss.accept();
System.out.println("Client Accepted!");
DataInputStream streamFromClient = new DataInputStream(client.getInputStream());
DataOutputStream streamToClient = new DataOutputStream(client.getOutputStream());
System.out.println("Connecting to server...");
// Make a connection to the real server.
server = new Socket("gamea.clashofclans.com", 9339);
System.out.println("Just connected client to " + server.getRemoteSocketAddress());
DataInputStream streamFromServer = new DataInputStream(server.getInputStream());
DataOutputStream streamToServer = new DataOutputStream(server.getOutputStream());
Thread t = new Thread() {
public void run() {
int bytesRead;
int type;
int size;
int version;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
type = streamFromClient.readUnsignedShort();
size = streamFromClient.readUnsignedShort();
size <<= 8;
size |= streamFromClient.readUnsignedByte();
version = streamFromClient.readUnsignedByte();
byte[] data = new byte[size];
streamFromClient.readFully(data, 0, size);
String FullHex = DatatypeConverter.printHexBinary(data);
System.out.println("Client sending data to server:");
System.out.println("Type: " + type + "");
System.out.println("Data Size: " + size + "");
System.out.println("Version: " + version + "");
System.out.println("Full Data: " + FullHex + "");
System.out.println("\n\n");
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
t.start();
int bytesRea;
int typ;
int siz;
try {
while ((bytesRea = streamFromServer.read(reply)) != -1) {
typ = streamFromServer.readUnsignedShort();
siz = streamFromServer.readUnsignedShort();
siz <<= 8;
siz |= streamFromServer.readUnsignedByte();
byte[] dat = new byte[siz];
streamFromServer.readFully(dat, 0, siz);
String FullHe = DatatypeConverter.printHexBinary(dat);
System.out.println("Server sending data to Client:");
System.out.println("Type: " + typ + "");
System.out.println("Data Size: " + siz + "");
System.out.println("Full Data: " + FullHe + "");
System.out.println("\n\n");
streamToClient.write(reply, 0, bytesRea);
streamToClient.flush();
}
} catch (IOException e) {
}
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
} catch (IOException e) {
}
}
}
}
}
This doesn't make sense. You're reading up to 4096 bytes from the server and then reading two type bytes and three length bytes and what you think is the request data, and writing what you read originally. So you're consuming the data about twice.
This can't work. You need to either just read the type, length, and value, and write them out again, or else, much more simply, just copy bytes from the input to the output, in both directions. (That way of course you can't do logging.)
NB Don't ignore IOExceptions, and especially not EOFExceptions when reading from DataInputStreams (or ObjectInputStreams).
When i call the http, and during it connection is cutt of..my app crashes.. how can i handle such issue in this code?
This also happens when there is no connection, and the http is called.. also it happens when i returns wrong format ( not json)..
HttpConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
// construct the URL
String serverURL = "xxxxxxxxxxxxxxxxxxxxxxx"+Common.getConnectionType();
// encode the parameters
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
byte[] postDataBytes = postData.getBytes();
// construct the connection
conn = (HttpConnection)Connector.open(serverURL, Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("User-Agent", "BlackBerry/" + DeviceInfo.getDeviceName() + " Software/" + DeviceInfo.getSoftwareVersion() + " Platform/" + DeviceInfo.getPlatformVersion());
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", new Integer(postDataBytes.length).toString());
// write the parameters
os = conn.openOutputStream();
os.write(postDataBytes);
// write the data and get the response code
int rc = conn.getResponseCode();
if(rc == HttpConnection.HTTP_OK) {
// read the response
ByteVector buffer = new ByteVector();
is = conn.openInputStream();
long len = conn.getLength();
int ch = 0;
// read content-length or until connection is closed
if( len != -1) {
for(int i =0 ; i < len ; i++ ) {
if((ch = is.read()) != -1) {
buffer.addElement((byte)ch);
}
}
} else {
while ((ch = is.read()) != -1) {
len = is.available();
buffer.addElement((byte)ch);
}
}
// set the response
accountsResponse = new String(buffer.getArray(), "UTF-8");
} else {
accountsResponse = null;
}
} catch(Exception e){
accountsResponse = null;
} finally {
try {
os.close();
} catch (Exception e) {
// handled by OS
}
try {
is.close();
} catch (Exception e) {
// handled by OS
}
try {
conn.close();
} catch (Exception e) {
// handled by OS
}
}
Hi i have a problem with my server, everytime i call "dload" the file gets downloaded but i can't use the other commands i have because they get returned as null. Anyone who can see the problem in the code?
Server :
public class TCPServer {
public static void main(String[] args) {
ServerSocket server = null;
Socket client;
// Default port number we are going to use
int portnumber = 1234;
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
// Create Server side socket
try {
server = new ServerSocket(portnumber);
} catch (IOException ie) {
System.out.println("Cannot open socket." + ie);
System.exit(1);
}
System.out.println("ServerSocket is created " + server);
// Wait for the data from the client and reply
boolean isConnected = true;
try {
// Listens for a connection to be made to
// this socket and accepts it. The method blocks until
// a connection is made
System.out.println("Waiting for connect request...");
client = server.accept();
System.out.println("Connect request is accepted...");
String clientHost = client.getInetAddress().getHostAddress();
int clientPort = client.getPort();
System.out.println("Client host = " + clientHost
+ " Client port = " + clientPort);
// Read data from the client
while (isConnected == true) {
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
String msgFromClient = br.readLine();
System.out.println("Message received from client = "
+ msgFromClient);
// Send response to the client
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("sum")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Double sum = 0.0;
for (int k = 0; k < 5; k++) {
sum = sum + list[k];
}
pw.println("Sum of array is " + sum);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("max")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Arrays.sort(list);
pw.println("Max integer in array is " + list[4]);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("time")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Time is:, "
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE);
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("date")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Date is: " + calendar.get(Calendar.DATE)
+ "/" + calendar.get(Calendar.MONTH) + "/"
+ calendar.get(Calendar.YEAR);
;
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("c2f")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
String celciusValue;
boolean ifRead = false;
try {
pw.println("Input celcius value");
celciusValue = br.readLine();
ifRead = true;
if (ifRead == true) {
double celcius = Double.parseDouble(celciusValue);
celcius = celcius * 9 / 5 + 32;
pw.println(celcius);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("dload")) {
OutputStream outToClient = client.getOutputStream();
if (outToClient != null) {
File myFile = new File("C:\\ftp\\pic.png");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0,
mybytearray.length);
outToClient.flush();
outToClient.close();
bis.close();
fis.close();
} catch (IOException ex) {
// Do exception handling
}
System.out.println("test");
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("quit")) {
client.close();
break;
}
// if (msgFromClient != null
// && !msgFromClient.equalsIgnoreCase("bye")) {
// OutputStream clientOut = client.getOutputStream();
// PrintWriter pw = new PrintWriter(clientOut, true);
// String ansMsg = "Hello, " + msgFromClient;
// pw.println(ansMsg);
// }
// Close sockets
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("bye")) {
server.close();
client.close();
break;
}
msgFromClient = null;
}
} catch (IOException ie) {
}
}
}
Client:
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String args[]) {
boolean isConnected = true;
Socket client = null;
int portnumber = 1234; // Default port number we are going to use
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
try {
String msg = "";
// Create a client socket
client = new Socket("127.0.0.1", 1234);
System.out.println("Client socket is created " + client);
// Create an output stream of the client socket
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
// Create an input stream of the client socket
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
// Create BufferedReader for a standard input
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
while (isConnected == true) {
System.out
.println("Commands: \n1. TIME\n2. DATE\n3. C2F\n4. MAX\n5. SUM\n6. DLOAD\n7. QUIT");
// Read data from standard input device and write it
// to the output stream of the client socket.
msg = stdIn.readLine().trim();
pw.println(msg);
// Read data from the input stream of the client socket.
if (msg.equalsIgnoreCase("dload")) {
byte[] aByte = new byte[1];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (clientIn != null) {
try {
FileOutputStream fos = new FileOutputStream("C:\\ftp\\pic.png");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = clientIn.read(aByte, 0, aByte.length);
do {
baos.write(aByte, 0, bytesRead);
bytesRead = clientIn.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
System.out.println("File is successfully downloaded to your selected directory"+ "\n" +"*-----------------*"+ "\n" );
} catch (IOException ex) {
System.out.println("Couldn't dowload the selected file, ERROR CODE "+ex);
}
}
}else{
System.out.println("Message returned from the server = "
+ br.readLine());
}
if (msg.equalsIgnoreCase("bye")) {
pw.close();
br.close();
break;
}
}
} catch (Exception e) {
}
}
}
debugged your code and have two hints:
1)
don't surpress your exceptions. handle them! first step would to print your stacktrace and this question on SO wouldn't ever be opened ;-) debug your code!
2)
outToClient.flush();
outToClient.close(); //is closing the socket implicitly
bis.close();
fis.close();
so in your second call the socket on server-side will already be closed.
first thing:
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
This can throw a NumberFormatException, and because args[0] is passed by the user you should handle this.
reading the code also this gave me a problem:
double DoubleValue = Double.parseDouble(value); // LINE 104
Throwing a NumberFormatException when I give c2f as command to the server. You definitively need to handle this exception anywhere in your code and give proper answer to the client, something like:
try{
double DoubleValue = Double.parseDouble(value);
}catch(NumberFormatException e){
// TELL THE CLIENT "ops, the number you inserted is not a valid double numer
}
(in short example, starting from this you have to enlarge the code)
while (isConnected == true) {
I cannot see it! why not use this?
while (isConnected) {
if (msgFromClient != null && msgFromClient.equalsIgnoreCase("sum")){
can be:
if("sum".equalsIgnoreCase(msgFromClient)){
in this case you have no problem with the NullPointerException. (if msgFromClient is null the statement is false).
By the way, date and time command are working fine for me. Check the others.
To fix dload i think you have to delete the line:
outToClient.close();
(EDIT: sorry to maxhax for the same answr, didn't see your answer while writing this)
When i use one jpeg image with this web-server its very slow to show the picture in the browser. But the same picture when i open using Apache web server its super fast.
What am i missing in my code which is so slow to render the jpeg file? Following is the code i am using:
server.java:
package www;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class server extends Thread
{
public server(int listen_port, webserver_starter to_send_message_to)
{
message_to = to_send_message_to;
port = listen_port;
this.start();
}
private void s(String s2)
{
message_to.send_message_to_window(s2);
}
private webserver_starter message_to;
private int port;
public void run()
{
ServerSocket serversocket = null;
s("The httpserver v. 0000000000\n\n");
try {
s("Trying to bind to localhost on port " + Integer.toString(port) + "...");
serversocket = new ServerSocket(port);
}catch (Exception e) {
s("\nFatal Error:" + e.getMessage());
System.exit(0);
return;
}
s("OK!\n");
while (true)
{
s("\nReady, Waiting for requests...\n");
try {
Socket connectionsocket = serversocket.accept();
InetAddress client = connectionsocket.getInetAddress();
s(client.getHostName() + " connected to server.\n");
BufferedReader input =
new BufferedReader(new InputStreamReader(connectionsocket.
getInputStream()));
DataOutputStream output =
new DataOutputStream(connectionsocket.getOutputStream());
http_handler(input, output);
} catch (Exception e) {
s("\nError:" + e.getMessage());
}
}
}
private void http_handler(BufferedReader input, DataOutputStream output)
{
int method = 0; //1 get, 2 head, 0 not supported
String http = new String(); //a bunch of strings to hold
String path = new String(); //the various things, what http v, what path,
String file = new String(); //what file
String user_agent = new String(); //what user_agent
try {
String tmp = input.readLine(); //read from the stream
String tmp2 = new String(tmp);
tmp.toUpperCase(); //convert it to uppercase
if (tmp.startsWith("GET")) { //compare it is it GET
method = 1;
} //if we set it to method 1
if (tmp.startsWith("HEAD")) { //same here is it HEAD
method = 2;
} //set method to 2
if (method == 0) {
try {
output.writeBytes(construct_http_header(501, 0));
output.close();
return;
}
catch (Exception e3) {
s("error:" + e3.getMessage());
}
}
int start = 0;
int end = 0;
for (int a = 0; a < tmp2.length(); a++) {
if (tmp2.charAt(a) == ' ' && start != 0) {
end = a;
break;
}
if (tmp2.charAt(a) == ' ' && start == 0) {
start = a;
}
}
path = tmp2.substring(start + 2, end);
}
catch (Exception e) {
s("errorr" + e.getMessage());
}
s("\nClient requested:" + new File(path).getAbsolutePath() + "\n");
FileInputStream requestedfile = null;
try {
requestedfile = new FileInputStream(path);
}
catch (Exception e) {
try {
output.writeBytes(construct_http_header(404, 0));
output.close();
}
catch (Exception e2) {}
;
s("error" + e.getMessage());
}
try {
int type_is = 0;
if (path.endsWith(".zip"))
{
type_is = 3;
}
if (path.endsWith(".jpg") || path.endsWith(".jpeg"))
{
type_is = 1;
}
if (path.endsWith(".gif"))
{
type_is = 2;
}
output.writeBytes(construct_http_header(200, 5));
if (method == 1)
{
while (true)
{
int b = requestedfile.read();
if (b == -1) {
break; //end of file
}
output.write(b);
}
}
output.close();
requestedfile.close();
}
catch (Exception e) {}
}
private String construct_http_header(int return_code, int file_type)
{
String s = "HTTP/1.0 ";
switch (return_code)
{
case 200:
s = s + "200 OK";
break;
case 400:
s = s + "400 Bad Request";
break;
case 403:
s = s + "403 Forbidden";
break;
case 404:
s = s + "404 Not Found";
break;
case 500:
s = s + "500 Internal Server Error";
break;
case 501:
s = s + "501 Not Implemented";
break;
}
s = s + "\r\n";
s = s + "Connection: close\r\n";
s = s + "Server: SimpleHTTPtutorial v0\r\n";
switch (file_type) {
case 0:
break;
case 1:
s = s + "Content-Type: image/jpeg\r\n";
break;
case 2:
s = s + "Content-Type: image/gif\r\n";
case 3:
s = s + "Content-Type: application/x-zip-compressed\r\n";
default:
//s = s + "Content-Type: text/html\r\n";
s = s + "Content-Type: image/jpeg\r\n";
break;
}
s = s + "\r\n";
return s;
}
}
Well here's the first thing I'd fix:
while (true)
{
int b = requestedfile.read();
if (b == -1) {
break; //end of file
}
output.write(b);
}
You're reading and writing a single byte at a time. That will be painfully slow. Read and write a whole buffer at a time instead:
byte[] buffer = new byte[32 * 1024]; // 32K is a reasonable buffer size
int bytesRead;
while ((bytesRead = requestedfile.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
}
There may well be other performance problems in your code - there are certainly a lot of things I'd change about it, including following Java naming conventions everywhere and certainly fixing this:
// You should basically *never* have this code
catch (Exception e){}
... but as you asked about the performance, that's the first bit I've checked for.