Sending TCP data from Android (as client) - no data being sent? - android

I'm trying to send data from my Android app to my PC over TCP.
The code is as follows:
Socket socket = new Socket("10.0.78.75", 50505);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
mStatusText.setText("Sending Data to PC");
output.println("Hello from Android");
mStatusText.setText("Data sent to PC");
socket.close();
mStatusText.setText("Socket closed");
I don't get any errors at all while doing this, however, the server application (written in C#) does not get any data.
It sees the client connect to it, and sees that data is being sent, however, the data string comes out empty... And thoughts on why this is happening?
PS: The server code is copied from the following site and has been tested with a C# TCP client.
http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server

Try putting an out.flush();out.close(); after the println(..);

I had the same problem and Haphazard's solutions wasn't good enough for me. I think that you should use (in this case) output.flush(); and output.close(); instead of out.flush(); and out.close();. And you have to remember about internet permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
after <uses-sdk> and before <application>

Total guess this one, but have you tried calling flush() on the output stream before closing?

Related

How do I go about sending data between 2 devices which are paired via Bluetooth in Android Studio?

I'm still new to Android studio and I'm having a lot of trouble with Bluetooth, I'm currently making an app where I need to send data between devices. I'm letting the phone's default Bluetooth setup do the pairing but now I need to know how to send the data, I know I need to use input and output streams but I don't know exactly how.
And yes I have searched all over Google, I've followed a lot of Bluetooth tutorials but none of them seem to really explain how to send data from one device to another.
Thanks in advance.
After you establish a secure/insecure connection via bluetooth the rest is just socket programming simply. That is lets think about sending a text. We convert the text to byte and send that by Java OutputStream. In the same manner for the data received we can get it by InputStream.
But remember you need to maintain bunch of code and thread/handler to maintain state and others. Though the basic thing is simply socket programming over Bluetooth socket using the Bluetooth adapter. Have a look at the below repository in github. This creates a chatroom over bluetooth. i.e it sends and receives string data
https://github.com/zahansafallwa/Android-bluetooth-chat-with-emoji/tree/master/app/src/main/java/com/zahan/safallwa/donttalk
Specially have a look at the BluetoothChatService class. That contains codes related to sending data. BluetoothChatService
Edit:
As per your comment lets think that your devices are paired and also connected. Now you only need to send the text. Declare a outputstream
private final OutputStream mmOutStream;
Suppose you have a string. We convert it to byte. Then get our socket outputstream and send data by write() method
String message="this is test data";
byte[] send = message.getBytes();
mmOutStream = socket.getOutputStream(); // here socket is the bluetooth socket you establish
mmOutStream.write(send);//this is what sends the message
Remember:
Edited code is for your understanding only. It is prescribed to use separate thread for sending data.

Android bluetooth socket data transfer and lifecycle

I am currently trying to send some data between two android devices using Bluetooth. I've read plenty of questions regarding bluetooth transfer, sockets, and streams. So far without any luck.
The connection part is working. I get the device address then open a connection using the following :
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(myOtherDeviceAdress);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString(myUUID));
socket.connect();
And then try to send some data using the OutputStream
OutputStream mmout=tmp.getOutputStream();
byte[] toSend="Hello World!".getBytes();
mmout.write(toSend);
mmout.flush();
On the receiving end:
mBluetoothServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("ccv_prototype", UUID.fromString(myUUID));
mBluetoothSocket = mBluetoothServerSocket.accept(3 * 1000);
InputStream is = mBluetoothSocket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
And then, different version trying to read the buffer, currently:
int c;
StringBuilder response = new StringBuilder();
try {
while ((c = r.read()) != -1) {
//Since c is an integer, cast it to a char. If it isn't -1, it will be in the correct range of char.
response.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
String result = response.toString();
Log.d("MyTag", "Received String: " + result);
My issue here is that if I don't close the OutputStream, the receiving end never receives the EOF, but if I add mmout.close();, it closes before it even had time to read the message I wanted to send. So far, my only idea is to send a specific token as an EOF but this doesn't sound right.
What did I miss ?
Any help appreciated.
The simple answer is yes. You should send a specific token to represent EOF. When you do a read() operation on a Bluetooth socket, it will either return immediately with some data if there's data ready to be read, or otherwise the read() call will block until there is some data, or some IO exception happens (e.g. the connection drops). This is why you must make use of Threads, particularly for Bluetooth socket read and write operations. What you're attempting to do is rely on the BufferedReader returning -1 to indicate "no more data". Sadly, this isn't how it works. The -1 will only happen in the event of some IO exception or the connection closing.
Detection of where your piece of information (i.e. your packet of data) starts and finishes, or indeed determining when an overall communication session is ended, is something that you handle yourself in your own application protocol (or of course an existing protocol) that works over the sockets. This is an important concept with any protocol that works through streaming sockets. A good example to look at is HTTP, which as you know is conventionally used over TCP. Taking a quick look at HTTP will show you (a) how the HTTP protocol uses headers to tell the recipient how many more bytes to expect for the overall HTTP "message", and (b) how HTTP headers are also used to negotiate when the connection should close. What you cannot do is attempt to use methods on the sockets themselves to determine when the sender has finished writing a message. Similarly if one end is to be aware that the other end wants to close the connection, that should be negotiated over the application protocol.

Android Sockets - My code is working 2.3.6 but not in 4.x

I'm newbie on Android and Java programming and I'm stuck.
I was able to create a TCP/IP communication client (Over LAN) which sends text messages on a windows based web server. The code is working quite well on my Samsung Galaxy S Advance mobile phone which is currently running on 2.3.6. However trying the apk file on two other devices running Android 4.0 and Android 4.1 the App is running but no message arrives on the PC (test are preformed on the same network).
The function I'm using for sending packets is the following:
public void sednit(String IP,String MSG) {
try {
// Socket s = new Socket ("192.168.128.102",39999);
Socket s = new Socket (ipaddress,39999);
//outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter (out);
output.println(MSG);
output.flush();
BufferedReader input = new BufferedReader (new InputStreamReader(s.getInputStream)));
//read line(s)
String st = input.readLine();
//Close connection
s.close();
} catch (Exception e) {
// Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Unable to communicate with player", Toast.LENGTH_LONG).show();
}
What Am I doing wrong?
Is there any limitation applied on Android 4 and newer or I have messed up my manifest file?
Thank you.
You are most likely getting a NetworkOnMainThread exception. Since Android Honeycomb, you are required to perform network operations in separate threads to improve UI responsiveness. The easiest ways to do this are to use an AsyncTask to manage your network operation if it's short, or to extend java.io.Thread if the connection needs to be maintained.
As Tomislav says in comment use Asynctask to network communication.
Also catch (Exception e) { Is an extremely bad Idea.. Catch the exceptions you are counting on, so that others may be thrown and you can see them. We have no idea what so ever what is going wrong with you program when you are doing this...
So please either do e.printStackTrace(); or remove the try/catch so we can get your logcat and help you.

How to transfer sqlite3 database between two Android devices using Socket?

I have read this Bluetooth Chat post, and this Transfer file post.And I have two real android devices ,not AVDs, my
intent is to set IP address and port in one device which acts as a Client while the other acts as a Server.
They are using WIFI,and I have connected both of them to PC respectively.Get into adb shell ,and ping each other.It works.
I have written client code like this:
Socket socket = new Socket("192.168.1.142",8888);
InputStream in = socket.getInputStream();
byte[] buffer = new byte[in.available()];
Toast.makeText(this, String.valueOf(in.available()), Toast.LENGTH_LONG).show();
in.read(buffer);
String msg = new String(buffer);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
and the Server:
ServerSocket server = new ServerSocket(8888);
while(true) {
Socket client = server.accept();
OutputStream out = client.getOutputStream();
String msg = "Hello Android!";
out.write(msg.getBytes());
client.close();
}
I have add this
<uses-permission android:name="android.permission.INTERNET" /> to manifest.
But no response. I have two questions:
1.Why there is no response in my client?
2.How to handle with sqlite3 database ,there must be something different with ordinary text files,but what is the difference?
Any suggestions will be very appreciated.
It would be unwise to transfer a sqlite3 .db between devices that may be differing make/model/manufacturer/etc. Rather, you should dump the schema and content of database to csv or sql and transfer that. You may want to compress the file too before transfer.
As for networking with Android. If you're using an AVD (emulator) then you're going to find it impossible or near impossible. Your proxy also plays a role in networking so you need to be warey of what it allows, how it's currently configured, and how it behaves (bugs, quirks, features). You should use a tool such as wireshark to inspect network comms and make sure that your App is even sending something out before worrying whether that something gets recieved.

TCP problem - hangs when reading server's response

I am trying to write client for Android which is supposed to communicate with PC server application on local network. Server app is written by my friend in C#. Currently there is an iPhone app that is using this server application with no problems.
I have very simple code for TCP client:
1. Socket s = new Socket(server, port);
2. OutputStream out = s.getOutputStream();
3. PrintWriter output = new PrintWriter(out);
4. output.println("ACTION=Next&VALUE=0&");
5. BufferedReader input = new BufferedReader(new nputStreamReader(s.getInputStream()));
6. String st = input.readLine();
I went through many TCP implementation examples, and they are all similar. Pretty much like my code above. My app freezes on line 6 when I try to read response from the server.
It doesn't cause any errors (no exceptions), nothing shows in debugger, just timeout error after awhile. Server is supposed to return string after executing my action in line 4.
I don't understand why this code hangs. Input is not NULL (I've checked it). I would expect some exception to be thrown or simply empty string to be returned.
So? What am I missing? Could it be problem with some special characters that server app is sending and android can't handle that? Do I need any special permission in my manifest?
I am positive that I have correct IP address and correct port number. I can see that on server application running on my PC.
Thanks.
String st = input.readLine(); Does this command make the program wait until something is being read or it just takes straight whatever is in the buffer. I guess you will need to check continuosly if something came from the server. I mean, you need one infinite loop, something like
While (True){
st = input.readLine();
This will check if anything came the whole time. If u dont use it and if String st = input.readLine(); command doesnt make the program wait, then your code will end without taking anything.
You of course need internet permission in the manifest.
If it were me I'd add instrumentation to the server so that it can tell you when there's been a connection, when that connection has received data, and when a reply is being sent. Or else run tcpdump on the server.
You could also temporarily try grabbing the input character by character rather than a whole line at a time.
Try to figure out how far the "conversation" is progressing so you can figure out where it is really getting stuck

Categories

Resources