TCP sockets returning strange thing in Java - java

I have socket application that i use for communication with a device.
When i open socket i can read status outputs from the machine.
Machine sends some data which is separated by comma ',' and i need to parse only numbers.
The problem is when i parse the data i recieve numbers but i also recieve "empty" strings.
Here is my code:
void startListenForTCP(String ipaddress) {
Thread TCPListenerThread;
TCPListenerThread = new Thread(new Runnable() {
#Override
public void run() {
Boolean run = true;
String serverMessage = null;
InetAddress serverAddr = null;
BufferedWriter out = null;
int redni = 0;
try {
Socket clientSocket = new Socket(ipaddress, 7420);
try {
mc.pushNumbers("Connection initiated... waiting for outputs!"
+ "\n");
char[] buffer = new char[2];
int charsRead = 0;
out =
new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((charsRead = in.read(buffer)) != -1) {
String message = new String(buffer).substring(0, charsRead);
if (message.equals("I,")) {
mc.pushNumbers("\n");
} else {
String m = message;
m = m.replaceAll("[^\\d.]", "");
String stabilo = m;
int length = stabilo.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = stabilo.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("Result:" + m);
}
}
} catch (UnknownHostException e) {
mc.pushNumbers("Unknown host..." + "\n");
} catch (IOException e) {
mc.pushNumbers("IO Error..." + "\n");
} finally {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
mc.pushNumbers("Connection refused by machine..." + "\n");
}
}
});
TCPListenerThread.start();
}
And the System.out.println(); returns this:
Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:26Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:13
Result:Result:Result:Result:Result:Result:Result:Result:Result:
I just don't know why I can't parse only numbers, there is probably something that machine sends and it isn't parsed by m = m.replaceAll("[^\\d.]", "");

You're building your String incorrectly. It should be:
String message = new String(buffer, 0, bytesRead);
where 'bytesRead' is the count returned by the read() method. It's a byte count, not a char count.

Related

Java - Find Server in network

I want to find my Server in my network, when I don't know the ip.
So that's the code I have, but it takes really (!) long to test all IPs:
for (int j = 1; j < 255; j++) {
for (int i = 1; i < 255; i++) {
String iIPv4 = "192.168." + j + ".";
try {
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(iIPv4 + i, 2652 );
socket.connect(address, 5);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fromServer;
while ((fromServer = in.readLine()) != null) {
if (fromServer.equals("Connected to CC3000")) {
System.out.println("CC3000 found! : " + iIPv4 + i);
return iIPv4 + i;
}
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
}
so, whats a better way to find the server?
regards
I think that multithreading could help you here, since you don't want to be waiting for each connection to either establish or fail.
You can try say hundreds of sockets at once instead. Also checking that IP is reachable might save you some time.
Code below is really a naive and horrible example since there's no thread management at all, but you get the picture I hope. You should get the result much faster.
public static void findLanSocket(final int port, final int timeout) {
List<Thread> pool = new ArrayList<>();
for (int j = 1; j < 255; j++) {
for (int i = 1; i < 255; i++) {
final String iIPv4 = "192.168." + j + "." + i;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("TESTING: " + iIPv4);
try {
// First check if IP is reachable at all.
InetAddress ip = InetAddress.getByName(iIPv4);
if (!ip.isReachable(timeout)) {
return;
}
// Address is reachable -> try connecting to socket.
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(ip, port);
socket.connect(address, timeout);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fromServer;
while ((fromServer = in.readLine()) != null) {
if (fromServer.equals("Connected to CC3000")) {
System.out.println("CC3000 found! : " + iIPv4);
}
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
});
pool.add(thread);
thread.start();
}
}
// Wait for threads to die.
for (Thread thread : pool) {
try {
if (thread.isAlive()) {
thread.join();
}
} catch (InterruptedException ex) {
}
}
}

Message returned is null

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)

multi client error with java multithreading

Below is the code for a client and server which handles multi user chat. But when one client writes "quit" my others current connected client also terminates and I can't then connect another client. Can anybody help with this?
Here is my client code:
class TCPClientsc {
public static void main(String argv[]) throws Exception {
String modifiedSentence;
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println(inetAddress);
Socket clientSocket = new Socket(inetAddress, 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
CThread write = new CThread(inFromServer, outToServer, 0, clientSocket);
CThread read = new CThread(inFromServer, outToServer, 1, clientSocket);
}
}
class CThread extends Thread {
BufferedReader inFromServer;
DataOutputStream outToServer;
Socket clientSocket = null;
int RW_Flag;
public CThread(BufferedReader in, DataOutputStream out, int rwFlag, Socket clSocket) {
inFromServer = in;
outToServer = out;
RW_Flag = rwFlag;
clientSocket = clSocket;
start();
}
public void run() {
String sentence;
try {
while (true) {
if (RW_Flag == 0) {// write
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
sentence = inFromUser.readLine();
// System.out.println("Writing ");
outToServer.writeBytes(sentence + '\n');
if (sentence.equals("quit"))
break;
} else if (RW_Flag == 1) {
sentence = inFromServer.readLine();
if (sentence.endsWith("quit"))
break;
System.out.println("(received)" + sentence);
}
}
} catch (Exception e) {
} finally {
try {
inFromServer.close();
outToServer.close();
clientSocket.close();
} catch (IOException ex) {
Logger.getLogger(CThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Server code:
class TCPServersc {
static int i = 0;
static SThread tt[] = new SThread[100];
static SThread anot[] = new SThread[100];
public static void main(String argv[]) throws Exception {
String client;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
i++;
System.out.println("connection :" + i);
BufferedReader inFromClient = new BufferedReader(newInputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader inFromMe = new BufferedReader(new InputStreamReader(System.in));
tt[i] = new SThread(inFromClient, outToClient, tt, 0, connectionSocket, i);
anot[i] = new SThread(inFromMe, outToClient, tt, 1, connectionSocket, i);
}
}
}
// ===========================================================
class SThread extends Thread {
BufferedReader inFromClient;
DataOutputStream outToClient;
String clientSentence;
SThread t[];
String client;
int status;
Socket connectionSocket;
int number;
public SThread(BufferedReader in, DataOutputStream out, SThread[] t, int status, Socket cn, int number) {
inFromClient = in;
outToClient = out;
this.t = t;
this.status = status;
connectionSocket = cn;
this.number = number;
start();
}
public void run() {
try {
if (status == 0) {
clientSentence = inFromClient.readLine();
StringTokenizer sentence = new StringTokenizer(clientSentence, " ");
// ///////////////////////////////////////////////////////////
if (sentence.nextToken().equals("login")) {
String user = sentence.nextToken();
String pass = sentence.nextToken();
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
int flag = 0;
while ((client = br.readLine()) != null) {
if ((user.equals(client.substring(0, 5))) && (pass.equals(client.substring(6, 10)))) {
flag = 1;
System.out.println(user + " has logged on");
for (int j = 1; j <= 20; j++) {
if (t[j] != null)
t[j].outToClient.writeBytes(user + " has logged on" + '\n');// '\n' is necessary
}
break;
}
}
if (flag == 1) {
while (true) {
clientSentence = inFromClient.readLine();
System.out.println(user + " : " + clientSentence);
for (int j = 1; j <= 20; j++) {
if (t[j] != null)
// '\n' is necessary
t[j].outToClient.writeBytes(user + " : " + clientSentence + '\n');
}
// if(clientSentence.equals("quit"))break;
}
}
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (status == 1) {
while (true) {
clientSentence = inFromClient.readLine();
if (clientSentence.equals("quit"))
break;
System.out.println("Server: " + clientSentence);
for (int j = 1; j <= 20; j++) {
if (t[j] != null)
t[j].outToClient.writeBytes("Server :" + clientSentence + '\n');// '\n' is necessary
}
}
}
} catch (Exception e) {
} finally {
try {
// System.out.println(this.t);
inFromClient.close();
outToClient.close();
connectionSocket.close();
} catch (IOException ex) {
Logger.getLogger(SThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
This code has a number of problems.
First off, in the future, please post smaller, concise code fragments that are well formatted. I just had to basically reformat everything in your post.
I see a couple of places where you are catching but doing nothing with exceptions. This is tremendously bad practice. At the least you should be printing/logging the exceptions you catch. I suspect this is contributing to your problems.
I find the RW_Flag very confusing. You should have two client threads then. One to write from System.in to the server and one to read. Don't have one client thread which does 2 things. Same with status flag in the server. That should be 2 different threads.
Instead of int flag = 0; in the server, that should be boolean loggedIn;. Make use of booleans in Java instead of C-style flags and use better variable names. The code readability will pay for itself. Same for status, RW_flag, etc..
Instead of huge code blocks, you should move contiguous code out to methods: handleSystemIn(), handleClient(), talkToServer(). Once you make more methods in the your code, and shrink down the individual code blocks, it makes it much more readable/debuggable/understandable.
You need to have a synchronized (tt) block around each usage of that array. Once you have multiple threads that are all using tt if the main accept thread adds to it, the updates need to be synchronized.
I don't immediately see the problem although the spagetti code is just too hard to parse. I suspect you are throwing and exception somewhere which is the reason why clients can't connect after the first one quits. Other than that, I would continue to use liberal use of System.out.println debugging to see what messages are being sent where.

How to optimize this web-server i am using with Java for rendering JPEG file only? Which is extream slow

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.

Parse string with delimiter ";" (java)

I have a string = "1.515 53.11 612.1 95.1 ; 0 0 0 0"
I'm tring to parse it via this code:
public class SendThread implements Runnable {
public void run()
{
socket = null;
BufferedReader in;
while (true)
{
// Loop until connected to server
while (socket == null){
try{
socket = new Socket ("192.168.137.1", 808);
}
catch (Exception e) {
socket = null;
//Log.d("Connection:", "Trying to connect...");
}
try {
Thread.sleep(30);
} catch (Exception e) {}
}
// Get from the server
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Connection: ", "connected");
String line = null;
while ((line = in.readLine()) != null) {
Log.d("Socket:", line);
NumberFormat nf = new DecimalFormat ("990,0");
String[] tokens = null;
String[] tempData = null;
String[] windData = null;
try {
tokens = line.split(";");
tempData = tokens[0].trim().split(" ");
windData = tokens[1].trim().split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
for (int i = 0; i < currentTemp.length; i++)
currentTemp[i] = (Double) nf.parse(tempData[i]);
for (int i = 0; i < currentWind.length; i++)
currentWind[i] = (Double) nf.parse(windData[i]);
//Toast.makeText(getApplicationContext(), "Received data:", duration)
for (int i = 0; i < currentTemp.length; i++){
Log.d("Converted data: currentTemp["+i+"] = ", currentTemp[i]+"");
}
for (int i = 0; i < currentWind.length; i++){
Log.d("Converted data: currentWind["+i+"] = ", currentWind[i]+"");
}
}
socket = null;
Log.d("Connection: ", "lost.");
}
catch (Exception e) {
socket = null;
Log.d("Connection: ", "lost.");
Log.d("Connection:", e+"");
}
}
}
}
Bad code :( But I don't know better way to hold the socket connection :)
I always get "java.text.ParseException: Unparseable number". How to fix it?
tokens, tempData, windData are String[]
Apart from what others said, I bet when you do
windData = tokens[1].split(" ");
you get
windDate = {"","0","0","0","0"}
and try to parse the first element as Number.
Try to do :
try {
tokens = line.split(";");
tempData = tokens[0].trim().split(" ");
windData = tokens[1].trim().split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
You don't need to escape the semicolon. Try just doing:
try {
tokens = line.split(";");
tempData = tokens[0].split(" ");
windData = tokens[1].split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
I suspect your parse error is because of the trailing space after the 95.1 in your input string. As it is, your tempData array will have 5 values, the last being ''. Trying to parse that as a number will give you that exception.
Hmm, your code (as posted) does not generate this exception. Secondly, "\\;" is redundant, you can write ";"
You could use, string tokenizer for that.
String s = "1.515 53.11 612.1 95.1 ; 0 0 0 0";
StringTokenizer tokenizer = new StringTokenizer(s,";");
while(tokenizer.hasMoreElements()){
StringTokenizer numberTokenize = new StringTokenizer(tokenizer.nextToken());
while(numberTokenize.hasMoreElements()) {
System.out.println(numberTokenize.nextElement());
}
}
Try using the \s in your split for whitespace; e.g. tempData = tokens[0].split("\s"); ... it represents a whitespace character.

Categories

Resources