I have an android app that I would like to make it be able compare data via wi-fi p2p.
I understand the connection method (1. Set up app. permissions; set up broadcast reciever and P2P manager; initiate peer descovery; connect to peer)
But I have a problem when it comes to data transfer. My app's interface has some drop-down menus
with several options to select from. I was wondering, how can I make the selected options (once the app users connect to each other)
be able to compare data and notify the app users if they have mutual selections.
Will this code work?
//SERVER
public static class FileServerAsyncTask extends AsyncTask {
private Context context;
private TextView statusText;
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
/**
* Create a server socket and wait for client connections. This
* call blocks until a connection is accepted from a client
*/
ServerSocket serverSocket = new ServerSocket(8888);
Socket client = serverSocket.accept();
/**
* If this code is reached, a client has connected and transferred data
*/
var pGender:String
var pDesire:String
var pAge:String
var pRace:String
var pWeight:String
var pHeight:String
var dGender:String = dGender.getValue(dGender.selectedItem.data);
var pDesire:String = pDesire.getValue(pDesire.selectedItem.data);
var dRace:String = dRace.getValue(dRace.selectedItem.data);
var dAge:String = dAge.getValue(dAge.selectedItem.data);
var dHeight:String = dHeight.getValue(dHeight.selectedItem.data);
var dWeight:String = dWeight.getValue(dWeight.selectedItem.data);
if (pGender == dGender.selectedItem.data && pDesire == pDesire.selectedItem.data && pRace == dRace.selectedItem.data && pWeight == dWeight.selectedItem.data && pHeight == dHeight.selectedItem.data)
{
trace (jump to frame 110 + vibrate);
}
else
{
trace (jump to frame 138 + vibrate + jump to frame 10) ;
}
return results;
}
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/**
* Start activity that can handle the JPEG image
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
}
Then the on the client I have this:
//CLIENT
Context context = this.getApplicationContext();
String host;
int port;
int len;
Socket socket = new Socket();
byte buf[] = new byte[1024];
...
try {
/**
* Create a client socket with the host,
* port, and timeout information.
*/
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), 500);
/**
* Create a byte stream from a JPEG file and pipe it to the output stream
* of the socket. This data will be retrieved by the server device.
*/
OutputStream outputStream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream inputStream = null;
/*varibles declaration
*/
pGender.getValue(pGender.selectedItem.data);
pDesire.getValue(pDesire.selectedItem.data);
pRace.getValue(pRace.selectedItem.data);
pAge.getValue(pAge.selectedItem.data);
pHeight.getValue(pHeight.selectedItem.data);
pWeight.getValue(pWeight.selectedItem.data);
inputStream = cr.openInputStream(Uri.parse(DataProvider.getItemAt(pGender:String, pDesire:String, pRace:String, pAge:String, pHeight:String, pWeight:String):Object));
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
//catch logic
} catch (IOException e) {
//catch logic
}
/**
* Clean up any open sockets when done
* transferring or if an exception occurred.
*/
finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
//catch logic
}
}
}
}
Related
I am using bluetoothconnection service on my fragment but ConnectedThread return empty. Although i am calling bluetoothconnection service but doesnt work. I dont find any solutions for this. How can i fix ?
Fragment:
if(convertView==null) {
convertView = inflater.inflate(R.layout.fragment_ota__update, container, false);
text=(TextView)convertView.findViewById(R.id.text);
InputStream is =this.getResources().openRawResource(R.raw.blink);
BufferedReader reader = new BufferedReader( new InputStreamReader(is));
send =(Button) convertView.findViewById(R.id.send);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver4, filter);
mBluetoothConnection = new BluetoothConnectionService(getActivity().getApplicationContext());
mBluetoothConnection.startClient(mBTDevice,MY_UUID_INSECURE);
if(is!=null){
try {
while ((data = reader.readLine()) != null) {
char [] ch =data.toCharArray();
for (char c: ch) {
int i= (int) c;
sbuffer.append(Integer.toHexString(i).toUpperCase());
text.setText(sbuffer);
}
}
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sbuffer!=null) {
byte[] bytes = sbuffer.toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
}
});
}
In the fragment i am calling with this code:
mBluetoothConnection = new BluetoothConnectionService(getActivity().getApplicationContext());
BluetoothConnectionService part of write function
public void write(byte[] out) {
if(mConnectedThread !=null ){
// Create temporary object
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
mConnectedThread.write(out);
}
else{
Log.d(TAG, "mConnectedThread empty ");
}
}
And this is my bluetooth connection class :https://paste.ubuntu.com/p/gcPrydZnDw/
Your code is not something I can fix directly. But I here is aan example of how I made a connection and then send data to this connected device:
public class BluetoothConnection extends Thread {
public static BluetoothSocket mSocket;
private InputStream mInStream;
private OutputStream mOutStream;
private byte[] buffer;
private BluetoothAdapter mAdapter;
private Handler mHandler;
private String output;
private String sendString;
private String tempTester = "";
static UUID MY_UUID;
/**
* Constructor initializes all necessary variables.
* #param device the device that the constructor will connect to
*/
public BluetoothConnection(BluetoothDevice device){
MY_UUID = device.getUuids()[0].getUuid();
mAdapter = null;
mSocket = createMSocket(device);
mSocket = connectSocket(mSocket);
InputStream tmpIn = null;
OutputStream tmpOut = null;
try{
tmpIn = mSocket.getInputStream();
tmpOut = mSocket.getOutputStream();
}catch (IOException e){
e.printStackTrace();
}
mInStream = tmpIn;
mOutStream = tmpOut;
buffer = new byte[25];
}// end constructor
/**
* Creates the main socket that will be used in connection with device.
* #param device a BluetoothDevice
* #return a BluetoothSocket mSocket.
*/
private BluetoothSocket createMSocket(BluetoothDevice device) {
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
return tmp;
}// end createMSocket
/**
* Socket makes connection to device then returns back the updated socket.
* #param socket BluetoothSocket
* #return an updated version of the parameter socket.
*/
private BluetoothSocket connectSocket(BluetoothSocket socket){
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
System.out.println("$$$$$$$$$$$$$$$$****** socket connected ******$$$$$$$$$$$$$$$$");
} catch (IOException e) {
//connection to device failed so close the socket
try {
socket.close();
System.out.println("$$$$$$$$$$$$$$$$****** socket closed ******$$$$$$$$$$$$$$$$");
} catch (IOException e2) {
e2.printStackTrace();
}
}
return socket;
}// end connectSocket
/**
* Sends message back to device in the form of a byte[].
* #param buffer byte[]
*/
public void write(byte[] buffer){
try{
mOutStream.write(buffer);
}catch(IOException e) {
e.printStackTrace();
}
}// end write
/**
* Closes the connection with the device
*/
public void cancel(){
try{
mSocket.close();
}catch(IOException e){
e.printStackTrace();
}
}// end cancel
}
Then on your main thread in an activity, you can call the following code (as long as you know the device you are connecting to):
BluetoothConnection connection = new BluetoothConnection(connectedDevice);
public void sendData(){
String s = editText.getText().toString();
byte[] b = s.getBytes();
connection.write(b);
//System.out.println("Bytes Sent");
}// end sendData
I am trying to write an android application that streams images taken from a first device, through the camera, to a second device with WiFi Direct.
I am trying to use this GitHub project, WiFiDIrectDemo, I managed to connect the devices and to send just one file.
When I try to send a second file I don't get any error and, from the logs, everything seems to work, but the second device doesn't get any file.
Is this a known issue? I have tried to look on the internet but I could not find anything that could help me.
I am attaching my File Transfer Service class:
public class FileTransferService extends IntentService {
Handler mHandler;
public static final int SOCKET_TIMEOUT = 50000; //ms
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public static int PORT = 8888;
public static final String inetaddress = "inetaddress";
public static final int ByteSize = 512;
public static final String Extension = "extension";
public static final String Filelength = "filelength";
public FileTransferService(String name) {
super(name);
}
public FileTransferService() {
super("FileTransferService");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
InputStream is = null;
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
String extension = intent.getExtras().getString(Extension);
String filelength = intent.getExtras().getString(Filelength);
try {
if(!socket.isConnected())
{
Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.setReuseAddress(true);
socket.connect((new InetSocketAddress(host, port)),5000); // ..,socket_timeout)
Log.e("File Transfer Service"," socket connect");
}
Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
Log.e("file transfer" +
" service", "get output stream");
ContentResolver cr = context.getContentResolver();
Long FileLength = Long.parseLong(filelength);
WiFiTransferModal transObj = null;
ObjectOutputStream oos = new ObjectOutputStream(stream);
if(transObj == null) transObj = new WiFiTransferModal();
transObj = new WiFiTransferModal(extension,FileLength);
oos.writeObject(transObj);
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
}
DeviceDetailFragment.copyFile(is, stream);
Log.d(WiFiDirectActivity.TAG, "Client: Data written");
oos.flush();
oos.close(); //close the ObjectOutputStream after sending data.
} catch (IOException e) {
Log.e("file transfer service","unable to connect: " + e.toString() );
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (Exception e) {
// Give up
e.printStackTrace();
Log.e("File transfer service","exception socket.close: " + e.toString());
}
}
}
else Log.e("file transfer service","socket is already null");
}
}
}
}
EDIT
Receiving code:
public class FileServerAsyncTask extends AsyncTask<String, String, String> {
// private TextView statusText;
private Context mFilecontext;
private String Extension, Key;
private File EncryptedFile;
private long ReceivedFileLength;
private int PORT;
public FileServerAsyncTask(Context context, int port) {
this.mFilecontext = context;
handler = new Handler();
this.PORT = port;
}
#Override
protected String doInBackground(String... params) {
try {
Log.e("device detail fragment", "File Async task port-> " + PORT);
ServerSocket serverSocket = new ServerSocket();
Log.e("device detail fragment"," new server");
serverSocket.setReuseAddress(true);
Log.e("device detail fragment","set reuse address");
serverSocket.bind(new InetSocketAddress(PORT));
Log.e("device detail fragment","socket bind");
Socket client = serverSocket.accept();
Log.e("device detail fragment "," socket client accept");
Log.e("Device detail fragment ", "client inet address" + client.getInetAddress());
WiFiClientIp = client.getInetAddress().getHostAddress();
Log.e("device detail fragment"," get client ip: " + WiFiClientIp);
ObjectInputStream ois = new ObjectInputStream(
client.getInputStream());
Log.e("device detail fragment","object input stream + " + ois.toString());
WiFiTransferModal obj = null;
String InetAddress;
try {
obj = (WiFiTransferModal) ois.readObject();
Log.e("device detail fragment"," read object");
if (obj != null) {
Log.e("device detail fragment"," obj != null ");
InetAddress = obj.getInetAddress();
Log.e("device detail fragment"," get inet address: " +
InetAddress);
if (InetAddress != null
&& InetAddress
.equalsIgnoreCase(FileTransferService.inetaddress)) {
SharedPreferencesHandler.setStringValues(mFilecontext,
mFilecontext.getString(R.string.pref_WiFiClientIp), WiFiClientIp);
//set boolean true which identify that this device will act as server.
SharedPreferencesHandler.setStringValues(mFilecontext,
mFilecontext.getString(R.string.pref_ServerBoolean), "true");
ois.close(); // close the ObjectOutputStream object
Log.e("device detail fragment"," output stream close");
// after saving
serverSocket.close();
Log.e("device detail fragment","close");
return "Demo";
}
Log.e("device detail fragment","FileName got from socket on other side->>> "+
obj.getFileName());
}
final File f = new File(
Environment.getExternalStorageDirectory() + "/"
+ FolderName + "/"
+ obj.getFileName());
Log.e("background"," new file f from inputstream");
File dirs = new File(f.getParent());
Log.e("device detail fragment"," f get parent()");
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.e("device detail fragment","create new file");
/**
* Receive file length and copy after it
*/
this.ReceivedFileLength = obj.getFileLength();
InputStream inputstream = client.getInputStream();
Log.e("device detail fragment","input stream client get input");
Message msg = Message.obtain();
msg.what = 1;
try
{
// send the images to the image view through handler
Bitmap bitmap = BitmapFactory.decodeStream(inputstream);
Log.e("device detail fragment", "decode stream");
Bundle b = new Bundle();
b.putParcelable("bitmap", bitmap);
msg.setData(b);
Log.e("device detail fragment","message: " + msg.toString());
messageHandler.sendMessage(msg);
}
catch (Exception e)
{
Log.e("device detail fragment","stream not decoded into bitmap with" +
"exception: " + e.toString());
}
copyRecievedFile(inputstream, new FileOutputStream(f),
ReceivedFileLength);
Log.e("device detail fragment","copy input stream into file");
ois.close(); // close the ObjectOutputStream object after saving
// file to storage.
Log.e("device detail fragment","ois close");
/**
* Set file related data and decrypt file in postExecute.
* */
this.Extension = obj.getFileName();
this.EncryptedFile = f;
final Uri uri = Uri.fromFile(f);
return f.getAbsolutePath();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
Log.e("device detail fragment", e.getMessage());
}
return "";
} catch (IOException e) {
Log.e("device detail fragment", e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
if (!result.equalsIgnoreCase("Demo")) {
Log.e("On Post Execute","result +" + result);
} else if (!TextUtils.isEmpty(result)) {
/**
* To initiate socket again we are initiating async task
* in this condition.
*/
FileServerAsyncTask FileServerobj = new
FileServerAsyncTask(mFilecontext, FileTransferService.PORT);
if (FileServerobj != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
FileServerobj.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
Log.e("Post Execute", "FileServerobj.execute on executor");
} else
{
FileServerobj.execute();
Log.e("Post Execute", "FileServerobj.execute");
}
}
}
}
}
#Override
protected void onPreExecute() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(mFilecontext);
}
if(imageView == null){
imageView = new ImageView(mFilecontext);
}
}
}
The server will receive a file and then opens it by letting the user choose an app to display the file. The server asynctask then has finished. So no new file can be received. So i do not believe you if you say that the logs tell that all is normal. Your client socket can not connect to begin with. All is intented behaviour.
* To initiate socket again we are initiating async task * in this condition..
Your code is not coming there.
You have to start an asynctask again to receive the next file.
I have implemented Socket for a multiplayer game using libGdx.
Client side
private void startClient(String ip, int port) {
SocketHints socketHints = new SocketHints();
// Socket will time our in 4 seconds
socketHints.connectTimeout = 4000;
//create the socket and connect to the server entered in the text box ( x.x.x.x format ) on port 9021
Socket socket = Gdx.net.newClientSocket(Net.Protocol.TCP, ip, port,
socketHints);
try {
System.out.println("JoinScreen.startClient");
// write our entered message to the stream
OutputStream out = socket.getOutputStream();
out.write("testtest shine \n".getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
Server code
private void startThreadServer() {
new Thread(new Runnable() {
#Override
public void run() {
System.out.println("HotspotHomeScreen.run");
ServerSocketHints serverSocketHint = new ServerSocketHints();
serverSocketHint.acceptTimeout = 0;
ServerSocket serverSocket = Gdx.net.newServerSocket(Net.Protocol.TCP, mPort, serverSocketHint);
String messageStr = null;
while (true) {
// Create a socket
Socket socket = serverSocket.accept(null);
System.out.println("while true");
int value = 0;
BufferedReader buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
try {
while ((value = buffer.read()) != -1) {
char c = (char) value;
if (value != 0 && value != 155)
messageStr = messageStr + c;
// Read to the next newline (\n) and display that text on labelMessage
System.out.println("HotspotHomeScreen.run " + buffer.readLine());
System.out.println("test messageStr = " + messageStr);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("testnjnihg test" + messageStr);
System.out.println("HostScreen last line");
}
}
}).start(); // And, start the thread running
}
The BufferedReader is invoked after starting the server on one device,but data cannot read. When I switch to debug mode, after reaching while ((value = buffer.read()) != -1) { the buffer shows all the data I sent in the debugger console,but the execution stops there. Sorry for my bad Language
I am having a bluetooth device . Basically i want my app to connect to the device and receive the data it sends.However so far i am able to connect to the bluetooth device,but i am not able to receive any inputs from it .
here is my problem:
i) DataInputStream.available() always return 0.
ii) If i use any breakpoint on line
bytes = input.read(buffer); // This will freeze doesn't show anything.
and line below it never executes
public class ConnectThread extends Thread{
final String TAG="ConnectThread";
private ReadThread mReadThread = null;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean isDeviceConnected;
public final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket mmSocket = null;
Handler mHandler;
BluetoothDevice bTdevice;
private DataInputStream mReadData = null;
public ConnectThread(BluetoothDevice bTdevice, Handler mHandler) {
super();
this.bTdevice = bTdevice;
this.mHandler = mHandler;
InputStream tmpIn = null;
OutputStream tmpOut = null;
BluetoothSocket socket;
try {
socket = bTdevice.createRfcommSocketToServiceRecord(MY_UUID);
System.out.println("**** Socket created using standard way******");
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
mmSocket = socket;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
#Override
public synchronized void run() {
// TODO Auto-generated method stub
super.run();
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
adapter.cancelDiscovery();
Log.i("***Bluetooth Adapter**", "Bluetooth Discovery Canceled");
}
if (mmSocket != null) {
mmSocket.connect();
Log.i("***Socket Connection Successful**", "Socket Connection Successful");
isDeviceConnected = true;
mReadData = new DataInputStream(mmSocket.getInputStream());
Log.i("***Read data**", "" + mReadData);
if (mReadThread == null) {
mReadThread=new ReadThread(mReadData,mmSocket);
mReadThread.start();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("***Error**", "Socket Connection failed");
e.printStackTrace();
try {
mmSocket.close();
isDeviceConnected = false;
} catch (IOException closeException) {
e.printStackTrace();
}
}
// mHandler.obtainMessage(DisplayBtdataActivity.SUCCESS_CONNECT,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
// Read the data from device
private class ReadThread extends Thread {
/** The input. */
private DataInputStream input;
/**
* Constructor for ReadThread.
*
* #param input
* DataInputStream
*/
private BluetoothSocket mSocket;
public ReadThread(DataInputStream input, BluetoothSocket socket) {
this.input = input;
this.mSocket = socket;
}
/**
* Method run.
*
* #see java.lang.Runnable#run()
*/
public synchronized void run() {
try {
Log.d(TAG, "ReadThread run");
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
bytes = input.available(); // always return 0
// bytes = mReadData.readInt();
Log.i("***Bytes data**", "" + bytes);// print 0
Log.i("***Data input stream**", "" + input); // Here input is not null
if (input != null) {
Log.i("***hello world**", "...");
while (isDeviceConnected) {
try {
bytes = input.read(buffer); // this code never executes
Log.i("**bytes data**", " " + bytes);
if (input != null) {
int len = input.readInt();
Log.i(TAG, "Response Length: " + len);
if (len > 65452) {// Short.MAX_VALUE*2
Log.i(TAG, "Error: Accesory and app are not in sync.");
continue;
}
Log.d(TAG, "Response Length: " + len);
Log.d(TAG, "Reading start time:" + System.currentTimeMillis());
byte[] buf = new byte[len];
Log.d(
TAG, "input.available() " + input.available());
if (input.available() > 0) {
input.readFully(buf);
System.out.println("Output:=");
}
Log.d(TAG, "Reading end time:" + System.currentTimeMillis());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
isDeviceConnected = false;
}
}
}
} catch (Exception e) {
e.printStackTrace();
isDeviceConnected = false;
Log.e(TAG, "catch block 3 " + e.toString());
}
}
}
}
In ReadThread.Run() - you have to move the code
bytes = input.available (); // Always return 0
into while loop
1, you use input before checking for null if (input! = null)
2, Data is sent continuously and is a high probability that when running thread do not come any data, so therefore you have to give input.available bytes = (); into a while loop.
3, You can try to modify data processing. In principle, quickly read the data in the temporary buffer, and then move to MainBuffer and then manipulated with it. An example is in c # .net Xamarin, but just for an example :
private const int BTLPacketSize = 1024;
private const int BTLdataSize = 65536;
private System.Object InternaldataReadLock = new System.Object();
private System.Object dataReadLock = new System.Object();
private byte[] InternaldataRead = new byte[BTLPacketSize];//posila 64Byte pakety (resp. 62, protoze 2 jsou status bytes)
private byte[] TempdataRead = new byte[BTLPacketSize];
private byte[] dataRead = new byte[BTLdataSize];//Tyto pameti pouzivaji cursorc -> musim ohlidat preteceni pameti//Max. prenos rychlost je 115200 b/s.
private bool continueRead = true;
public override void Run()
{
while (continueRead)
{
try
{
int readBytes = 0;
lock (InternaldataReadLock)
{//Quick reads data into bigger InternaldataRead buffer and next move only "received bytes" readBytes into TempdataRead buffer
readBytes = clientSocketInStream.Read(InternaldataRead, 0, InternaldataRead.Length);
Array.Copy(InternaldataRead, TempdataRead, readBytes);
}
if (readBytes > 0)
{//If something reads move it from TempdataRead into main dataRead buffer a send it into MainThread for processing.
lock (dataReadLock)
{
dataRead = new byte[readBytes];
for (int i = 0; i < readBytes; i++)
{
dataRead[i] = TempdataRead[i];
}
}
Bundle dataBundle = new Bundle();
dataBundle.PutByteArray("Data", dataRead);
Message message = btlManager.sourceHandler.ObtainMessage();
message.What = 1;
message.Data = dataBundle;
btlManager.sourceHandler.SendMessage(message);
}
}
catch (System.Exception e)
{
if (e is Java.IO.IOException)
{
//.....
}
}
}
}
My android app connects the server with TCP socket, to make sure the connection is ok, the server sends the "keep-alive" msg every 10s when idle, I can grab the packet in WireShark, but in my app, I can't handle the packet anywhere, seems that the packet can't be read with the socket.
Below is the code segment of my socket connection. Seems that the "keep-alive" packet just can't be read with the inputstream...
public class SocketBase {
private Socket mSocket;
private DataOutputStream out;
private DataInputStream in;
private SocketCallback callback;
private int timeOut = 1000 * 30;
public SocketBase(SocketCallback callback) {
this.callback = callback;
}
public void connect(String ip, int port) throws Exception {
mSocket = new Socket();
SocketAddress address = new InetSocketAddress(ip, port);
mSocket.connect(address, timeOut);
if (mSocket.isConnected()) {
out = new DataOutputStream(mSocket.getOutputStream());
in = new DataInputStream(mSocket.getInputStream());
callback.connected();
}
}
public void write(byte[] buffer) throws IOException {
if (out != null) {
out.write(buffer);
out.flush();
}
}
public void disconnect() {
try {
if (mSocket != null) {
if (!mSocket.isInputShutdown()) {
mSocket.shutdownInput();
}
if (!mSocket.isOutputShutdown()) {
mSocket.shutdownOutput();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
mSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
callback.disconnect();
out = null;
in = null;
mSocket = null;
}
}
public void read() throws IOException {
if (in != null) {
byte[] buffer = new byte[1024*1];
byte[] tmpBuffer;
int len = 0;
Log.i("SOCKET", "something comming");
while ((len = in.read(buffer)) > 0) {
tmpBuffer = new byte[len];
System.arraycopy(buffer, 0, tmpBuffer, 0, len);
callback.receive(tmpBuffer);
tmpBuffer = null;
}
}
}
}
The "keep-alive" packet in WireShark is like this:
If you mean a regular TCP keep-alive, there's nothing for you to detect or do. Your TCP implementation takes care of acknowledging it. There's no application data in it, so there's nothing for you to read.