I referenced the code from Android Developer. After compliling the code and fooling around with some of the errors, I could not figure this one out.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import junit.framework.TestCase;
public class ConnectedThread extends Thread {
private static final String MESSAGE_READ = null;
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private Handler mHandler = new Handler();
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}
catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
// buffer store for the stream
int bytes;
// bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main Activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
}
catch (IOException e) { }
}
/* Call this from the main Activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
The method obtainMessage(int, int , object) in the type Handler is not applicable for the arguments(String, int ,int, Byte[]).
Could someone that has used this code before possibly tell me what i need to ad or what i am missing. Its probably something really simple. Thank You.
obtainMessage accept argumets like
handler.obtainMessage(int)
handler.obtainMessage(int, object)
handler.obtainMessage(int, int, int)
handler.obtainMessage(int, int, int, object);
You have passes MESSAGE_READ variable in handler.obtainMessage() so it looks like
handler.obtainMessage(String, int, int, object);
MESSAGE_READ which is String and thats why you are getting this error
change MESSAGE_READ variable String to Int
Related
I have this method to deserialize:
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
Object res = is.readObject();
is.close();
in.close();
return res;
}
and this one to serialize:
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
byte[] res = out.toByteArray();
out.close();
os.close();
return res;
}
I use these methods to serialize and deserialize a class object, that only has a string and an arrayList of another class, exchanged between 2 devices. Both the class of the object and the class of the arrayList implement serializable.
When I send an object with up to 3 elements in the arrayList these methods work perfectly. However, when the arrayList has 4 or more elements, the device receiving the object still detects that some data has "arrived" but the deserialize method generates an "EOFException" in the "Object res = is.readObject();" line.
Any ideas about what the problem could be ?
EDIT
This is the class of the arrayList:
import java.io.Serializable;
public class Info implements Serializable {
public Info() {
...
}
...
}
This is the class of the object:
import java.io.Serializable;
import java.util.ArrayList;
public class BluetoothDataContainer implements Serializable{
private ArrayList<Info> dataList;
private String originDevice;
public BluetoothDataContainer(String originDevice){
dataList= new ArrayList<Info>();
this.originDevice = originDevice;
}
...
}
This is the code I use to send the object:
BluetoothDataContainer data = new BluetoothDataContainer(mBluetoothAdapter.getName());
...
// add needed info to variable 'data'
...
s.write(data);
Where 's' is a thread with the method 'write':
private BluetoothSocket mmSocket = bluetoothDevice.createRfcommSocketToServiceRecord(ID_CONNECTION);
private OutputStream mmOutStream = mmSocket.getOutputStream();
...
public void write(BluetoothDataContainer m) {
try {
mmOutStream.write(serialize(m));
} catch (IOException e) {
this.mContext.showToast("IOException caught in thread ConnectedThread [Bluetooth connection handler] - write() !");
}
//cancel();
this.interrupt();
}
And this is how I handle the object when it is read:
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
final BluetoothDataContainer data;
try {
data = (BluetoothDataContainer) deserialize(readBuf);
...
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
};
And this is how I read the object:
private final Handler mHandler; // value set in the constructor
...
public void run() {
mmInStream = bluetoothSocket.getInputStream();
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes;
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
this.mContext.showToast("ConnectedThread [Bluetooth connection handler] data received !");
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(1, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
this.mContext.showToast("IOException caught in thread ConnectedThread [Bluetooth connection handler] - run() !");
}
}
Clearly you have not 'exchanged' the entire byte array in the case that fails.
bytes = mmInStream.read(buffer);
You can't possibly know from this alone whether you've read:
an entire message
less than one message
more than one message.
As you already have a socket with input and output streams, it beats me why you are creating byte arrays at all. Just wrap the ObjectOutputStream around the socket output stream and use writeObject(). At the receiver, wrap the ObjectInputStream around the socket input stream and use readObject().
NB you should use the same object streams for the life of the socket, and if you are sending objects both ways you must create the object output stream before the object input stream for the same socket: otherwise you can get a deadlock.
I'm kind of new to Android and I have a task to open a TCP socket and listen to a specific port.
A client application is supposed to send me 2 images and a string that are related to each other so instead of sending each data alone we thought about putting all data in a json object and send this object.
My question is, how do I parse this json into saving 2 images and a string?
So this json is supposed to be like this:
data
{
FileName: "some string",
Image1: "Image encoded with encode base64",
Image2: "Image encoded with encode base64"
}
I'm using an AsyncTask so here is the code where I get the socket data:
public class DataRecord
{
String Image1;
String Image2;
String FileName;
}
protected DataRecord doInBackground(Socket... sockets) {
DataRecord dataRecord = null;
if (isExternalStorageWritable() && sockets.length > 0) {
Socket socket = sockets[0];
dataRecord = socket.getOutputStream(); // how to extract the data from the socket into this object ???
File file = new File(Environment.getExternalStorageDirectory(), dataRecord.FileName);
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream inputStream;
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
inputStream.read(bytes, 0, bytes.length);
OutputStream outputStream = dataRecord.Image1;
outputStream.write(bytes, 0, bytes.length);
outputStream.flush();
socket.close();
}
catch (Exception e) { }
finally {
try {
socket.close();
} catch (IOException e) { }
}
}
return dataRecord;
}
And I need to get it from the socket object and extract an object from it to save the 2 images to the SD card and extract the string to the UI.
I know this question probably have more than one answer, but still posting an answer is a good idea.
So, I found this link here A Simple Java TCP Server and TCP Client which helped me getting started with my solution.
I've also used Gson to parse my JSON string using this nice tutorial: Android JSON Parsing with Gson Tutorial.
Finally, my code looks like this:
ServerSockerThread.java - this is the java class for the listening server which waits for incoming files:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketThread extends Thread {
static final int SocketServerPORT = 6789;
ServerSocket serverSocket;
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
while (true) {
socket = serverSocket.accept();
new FileSaveThread().execute(socket);
}
}
catch (IOException e) { }
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) { }
}
}
}
protected void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
}
catch (IOException e) { }
}
}
}
FileSaveThread.java - this is the java class that is being called by the above server class for each incoming file:
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Base64;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.Socket;
public class FileSaveThread extends AsyncTask<Socket, Void, DataRecord> {
#Override
protected void onPostExecute(DataRecord dataRecord) {
super.onPostExecute(dataRecord);
}
#Override
protected DataRecord doInBackground(Socket... sockets) {
DataRecord dataRecord = null;
if (isExternalStorageWritable() && sockets.length > 0) {
Socket socket = sockets[0];
try {
Gson gson = new Gson();
Reader reader = new InputStreamReader(socket.getInputStream());
SocketObject socketObject = gson.fromJson(reader, SocketObject.class);
SaveFileToSDCard(socketObject.Image1, "Image1.png");
SaveFileToSDCard(socketObject.Image2, "Image2.png");
SaveFileToSDCard(socketObject.Image3, "Image3.png");
dataRecord = new DataRecord(socketObject.Name);
}
catch (Exception e) { }
finally {
try {
socket.close();
} catch (IOException e) { }
}
}
return dataRecord;
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
private void SaveFileToSDCard(String base64String, String fileName) throws IOException {
byte[] decodedString = Base64.decode(base64String.getBytes(), android.util.Base64.DEFAULT);
File file = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file, false);
fileOutputStream.write(decodedString);
fileOutputStream.close();
fileOutputStream.flush();
}
}
i'm making a program/game that will update automatically. i have the update part down, but not the checking of the version. i would have thought that it'd be pretty easy. heres what i've done. i wrote an updater for the game, and i wrote a server. the server starts a thread every time a client/updater connects. the thread handles everything. the game updater reads a file called version.txt and that provides the version number (default 0.0.1) and sends it to the server. the server does recieve the version, and will System.out.println(); if the version matches, and if i change the version, it changes the output. so that part works. but that is as far as it goes. the second part of the process is that the server then sends just a text file called NPS Game.txt (it sends anything, but txt was easy to test with) and the client replaces the old version of this file with the new one that just sent. the problem is that i keep getting an error that says the Socket is closed. i've tried using socket.setKeepAlive(true); but that didnt change anything (i put that on both the client and the server). here is the code:
server:
package main;
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class Server {
static ServerSocket serverSocket = null;
static Socket clientSocket = null;
static boolean listening = true;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(6987);
} catch (IOException e) {
ServerThread.showmsg("Could not use port: 6987");
System.exit(-1);
}
ServerThread.showmsg("server- initialized");
ServerThread.showmsg("server- waiting...");
while (listening)
new ServerThread(serverSocket.accept()).start();
}
}
server thread:
package main;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import javax.swing.JOptionPane;
public class ServerThread extends Thread {
Socket socket;
ObjectInputStream in;
ObjectOutputStream out;
String version = "0.0.1";
public ServerThread(Socket socket) {
super("Server Thread");
this.socket = socket;
}
public void run() {
showmsg("server- Accepted connection : " + socket);
getVersion();
sendFile();
}
public void getVersion() {
try {
ObjectInputStream ois = new ObjectInputStream(
socket.getInputStream());
try {
String s = (String) ois.readObject();
if (s.equals(version)) {
System.out.println("server- matched version :)");
} else {
System.out.println("server- didnt match version :(");
System.exit(0);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendFile() {
// sendfile
File myFile = new File("C:\\Programming\\NPS\\Files\\bin\\NPS Game.txt");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis;
try {
fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
showmsg("server- Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
socket.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void showmsg(String s) {
JOptionPane.showMessageDialog(null, s);
}
}
and the client/updater:
package main;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import org.omg.CORBA.portable.InputStream;
public class Connections {
String IP, port;
String message = "";
Socket socket;
public Connections(boolean server, boolean updating, String IP, String port) {
this.IP = IP;
this.port = port;
try {
socket = new Socket(IP, Integer.parseInt(port));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (!server) {
if (updating) {
try {
sendVersion();
updating();
} catch (IOException e) {
e.printStackTrace();
}
} else {
client();
}
}
if (server) {
}
}
public void sendVersion() throws IOException {
FileReader fileReader = new FileReader(
"C:\\Program Files\\AVTECH\\NPS\\Files\\bin\\version.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String stringRead = bufferedReader.readLine();
bufferedReader.close();
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
oos.writeObject(stringRead);
oos.flush();
oos.close();
}
public void updating() throws IOException {
int filesize = 6022386; // filesize temporary hardcoded
int bytesRead;
int current = 0;
showmsg("client- connected");
// receive file
byte[] byteArray = new byte[filesize];
java.io.InputStream inStream = socket.getInputStream();
FileOutputStream fileOutStream = new FileOutputStream(
"C:\\Program Files\\AVTECH\\NPS\\Files\\bin\\NPS Game.txt");
BufferedOutputStream buffOutStream = new BufferedOutputStream(
fileOutStream);
bytesRead = inStream.read(byteArray, 0, byteArray.length);
current = bytesRead;
do {
bytesRead = inStream.read(byteArray, current,
(byteArray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
buffOutStream.write(byteArray, 0, current);
buffOutStream.flush();
buffOutStream.close();
inStream.close();
socket.close();
}
public static void showmsg(String s) {
JOptionPane.showMessageDialog(null, s);
}
}
i dont know what's wrong with it, but it is really frusturating. if anyone can help, it would be appreciated. some things ive done: google all kinds of questions, tried implementing socket.setKeepAlive(true);. also, i thought it might be of note, in the server thread, right above the line BufferedInputStream bis = new BufferedInputStream(fis);, i put System.out.println(socket.isClosed); and it returned true. thats all i have. thanks in advance!
I think that closing one of both streams, closes the socket. So try to remove the ois.close() call out of your getVersion() method at the server side. Also get rid of the oos.close() call in your sendVersion() method at the client side.
When you construct an ObjectOutputStream or ObjectInputStream and you are done with it, you shouldn't close that stream, because it will close the underlying stream, which is in your case the socket.
I am writing an app that makes use of Object Output and Input Streams. However I have a problem, because I am not able to send my object properly. I write it to stream, and server gives me a class not found exception, even though both client and server have exactly the same copy of this class (the only difference is the package name) with the same serial id. Here is my class:
import java.io.Serializable;
public class Message implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username = null;
private String hashedPassword = null;
private Integer code = null;
private String from = null;
private String to = null;
private Object data = null;
public Message() {
}
public Message(Integer code) {
this.code = code;
}
public Message(Integer code, Object data) {
this.code = code;
this.data = data;
}
public Message(String username, String hashedPassword, Integer code,
String from, String to, Object data) {
this.username = username;
this.hashedPassword = hashedPassword;
this.code = code;
this.from = from;
this.to = to;
this.data = data;
}
public Integer getCode() {
return code;
}
//other getters and setters
}
That is the class which object i want to send. Here is the client code:
(It is wirtten just for testing)
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 5656);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
Message m = new Message("user3", "123", 100, "2011-06-11 22:22:22",
"2011-06-11 22:22:22", "test");
oos.writeObject(m);
oos.flush();
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
Message n = (Message) ois.readObject();
System.out.print(n.toString());
oos.close();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
and here is part of server code (yes it is multithreaded):
package systemZarzadzaniaReporterami.serwer;
import java.beans.ExceptionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.SQLException;
public class ClientHandler extends Thread {
private ExceptionListener exceptionListener;
private Socket socket;
private String ip;
public ClientHandler(ExceptionListener exceptionListener, Socket socket) {
this.exceptionListener = exceptionListener;
this.socket = socket;
ip = socket.getInetAddress().getHostAddress();
}
public void run() {
Message in = null;
ObjectInputStream inputStream = null;
ObjectOutputStream outputStream = null;
try {
// ClientListener.CONNECTION_COUNTER++;
inputStream = new ObjectInputStream(socket.getInputStream());
in = (Message) inputStream.readObject();
MessageProcessor messageProcessor = new MessageProcessor();
System.out.print(in.getUsername());
outputStream = new ObjectOutputStream(socket.getOutputStream());
Message out = messageProcessor.process(in, ip);
System.out.print(in.getCode().toString());
outputStream.writeObject(out);
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
exceptionListener.exceptionThrown(new ServerException(Codes.ERR_CONNECTION_ERROR));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
exceptionListener.exceptionThrown(new ServerException(Codes.ERR_MYSQL_ERROR));
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
exceptionListener.exceptionThrown(new ServerException(Codes.ERR_CONNECTION_ERROR));
}
if (outputStream != null)
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
exceptionListener.exceptionThrown(new ServerException(Codes.ERR_CONNECTION_ERROR));
}
if (socket != null)
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
exceptionListener.exceptionThrown(new ServerException(Codes.ERR_CONNECTION_ERROR));
}
// ClientListener.CONNECTION_COUNTER--;
}
}
}
I am pretty confused now. Because I have no idea why is such thing happening.
What is most important in my opinion that the following code does well when I replace Message with string.
the only difference is the package name
That won't work. The class name (including the package name) must be the same on both sides.
the only difference is the package name
Then they are not the same class. Make sure you have exactly the same class on both sides. That means same package.
hi to all i have created a server class with threadpool as shown below and it makes use of workerRunnable class . the problem i am facing with this code is when i am trying to send files from two cliensts at same time to this server,it is giving me a irregular response (in the sense first thread wil run till next client request is made as soon as the request cums from the second client it stops the first one and starts working on the second req and second one response is sent to both the clients sockets instead of sending their respective response)...pls can any one tell me where i am going wrong?????
package com.tel.snmp;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPooledServer implements Runnable{
protected int serverPort = 4444;//hk
protected ServerSocket serverSocket = null;
protected boolean isStopped = false;
protected Thread runningThread= null;
public BlockingQueue q = new ArrayBlockingQueue(20);
public static int clientconnection = 0;
ThreadPoolExecutor threadpool = new ThreadPoolExecutor(4,10,20,TimeUnit.SECONDS,q);
public ThreadPooledServer(int port){
this.serverPort = port; // wrk2
}
public void run()
{
synchronized(this)
{
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(! isStopped()){
Socket clientSocket = null;
try
{
//System.out.println("the value of client connection BEFORE is"+clientconnection);
clientSocket = this.serverSocket.accept();
clientconnection++;
System.out.println("the value of client connection is"+clientconnection);
} catch (IOException e)
{
if(isStopped())
{
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException(
"Error accepting client connection", e);
}
this.threadpool.execute(new WorkerRunnable(clientSocket,"Thread pooled server"));
}
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); //wrkr2
}
catch (IOException e) {
throw new RuntimeException("Cannot open port serverPort"+serverPort, e);
}
}
}
-----------------------------Worker Runnable class-----------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tel.snmp;
/**
*
* #author harikrishnadv
*/
import com.tel.common.ProtocolSelector;
import java.io.*;
import java.net.*;
/*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();
}
}
}
*/
public class WorkerRunnable implements Runnable
{
FileInputStream fis;
FileOutputStream fos;
BufferedInputStream bis;
BufferedOutputStream bos;
String filename="clientfile";
String fname=null;
//Socket soc;
int flag=0;
int ch;
//static int count=0;// new
protected Socket clientSocket = null;
protected String serverText = null;
public WorkerRunnable(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
public synchronized void run() {
try {
receiveFile();
/*try{
this.wait();
}
catch(InterruptedException i)
{
}*/
if(flag==1)
{
System.out.println("**********************************************************************************************************************************");
sendFile();
}
closeAll();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/** Method to send the response file to the client */
public void sendFile() throws IOException {
// SENDING A FILE
//String sendfile=EMS.fileprocessname+EMS.clientcount+".xml";
String sendfile=EM.fileprocessname;//+EM.clientcount;
System.out.println("filename that has been sending to client is"+sendfile);
bos = new BufferedOutputStream(clientSocket.getOutputStream());
//fis = new FileInputStream("C://outputs.xml");
fis = new FileInputStream(sendfile);
while ((ch = fis.read()) != -1) {
bos.write(ch);
bos.flush();
}
bos.write(-1);
bos.flush();
System.out.println("File Sent to :: " + clientSocket);
fis.close();
}
/** Method to receive input file from client */
public void receiveFile() throws IOException {
// RECEIVING A FILE
fname="C://"+filename+ThreadPooledServer.clientconnection+".xml";
bis = new BufferedInputStream(clientSocket.getInputStream());
//fos = new FileOutputStream("C://client.xml");
fos = new FileOutputStream(fname);
while ((ch = bis.read()) != 255) {
fos.write(ch);
fos.flush();
}
System.out.println("File Received from :: " +clientSocket);
fos.close();
if(flag==0){
ProtocolSelector m=new ProtocolSelector();
//m.xmldecider("C://client.xml");
m.xmldecider(fname);
flag=1;
}
}
public void closeAll() throws IOException {
bis.close();
bos.close();
}
}
i wil be thankful for ur valuable reply's
Your clientconnection field is static but is then accessed from your WorkerRunnable receiveFile() method. By the time the receiveFile() method executes there is no guarantee that the value of clientconnection is still correct - another client might have come along and incremented it.
Try changing your WorkerRunnable constructor to take the clientconnection as an argument e.g.
Change:
this.threadpool.execute(new WorkerRunnable(clientSocket,
"Thread pooled server"));
to:
this.threadpool.execute(new WorkerRunnable(clientSocket, clientconnection,
"Thread pooled server"));
Add a clientconnection field to your WorkerRunnable and then change this line:
fname="C://"+filename+ThreadPooledServer.clientconnection+".xml";
to:
fname="C://"+filename+clientconnection+".xml";