TCP/IP Android Device Connectivity Issues - java

I have a tcp/ip application in which Client 'A' gets it's coordinates and sends them to the server running on my pc. I am using local ips etc. This was running fine, I came out this morning however and I had an issue with my tp-link router and the lan, so I re installed my router and all connections (wi-fi) are back up and running. However, now when I try to run my app it won't work with my device.
If I run it through the emulator (i just have a string for testing) it works, I know that this is because both the server and the emulator are both on the same machine. My ip is correct, it is that of the machine the server is running on...I'm trying to teach myself this technology and do a project for college and I keep coming up against massive headaches like this. I've posted my client and server code below, is there anyone that might have any ideas? All setting are the same on the router and i'm sure as this is just connecting over a lan I don't have to forward any ports?
CLIENT A
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class Child extends Activity implements LocationListener {
private Socket s;
private PrintWriter p;
public static double latitude;
public static double longitude;
String coordinates;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.child);
LocationManager mlocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocationListener = new MyLocationListener();
mlocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mlocationListener);
String hello = "hello"; //FOR TESTING PURPOSES
Transmit (hello);
Log.d("test", "test");
}
public class MyLocationListener implements LocationListener {
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
longitude = location.getLongitude();
coordinates = ("TESTING " + latitude + longitude);
//Transmit(coordinates);
}
}
private void Transmit(final String message) {
Thread trans = new Thread(new Runnable() {
public void run() {
Log.d("TRANSMIT", "CALLED");
// TODO Auto-generated method stub
try {
s = new Socket("192.168.3.103", 1111); // connect to
// server
Log.d("CONNECTED", "Connected");
DataOutputStream _OutPut = new DataOutputStream(
s.getOutputStream());
_OutPut.writeBytes(message + "\n");
_OutPut.flush();
_OutPut.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
trans.start();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
SERVER
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class TCPServer {
public static void main(String[] args) throws Exception {
Socket s;
ServerSocket ss = new ServerSocket(1111);
System.out.println("Server started. Listening to the port 2001");
System.out.println("Server: waiting for connection ..");
while (true) {
try {
s = ss.accept();
if (s != null) {
InputStream fromChild = s.getInputStream();
while (s.isConnected()) {
System.out.println("Child Connected");
Scanner r = new Scanner(fromChild);
String location;
location = r.nextLine();
System.out.println(location);
}
}
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
So please, if anyone can help or throw some light on the situation I would be extremely grateful as I can't develop any further until I sort this problem.
Regards,
Gary

It certainly sounds like a connectivity issue between the phone and the server.
Double-check your ip address on the server and the phone and make sure they are on the SAME SUBNET (192.168.3.X), if not then you need to set up a forwarding rule on the router.
You can also verify connectivity by running a basic html server on the server box and point the browser on the phone to the server. Apache tomcat right of the box is easy to start and has a dashboard app already configured to run on startup. You can also test this from another computer on the same network to rule out your code and the phone altogether.

Read this:
http://developer.android.com/tools/devices/emulator.html#emulatornetworking
an excerpt from there :
Network Address Description
10.0.2.1 Router/gateway address
10.0.2.2 Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
10.0.2.3 First DNS server
10.0.2.4 / 10.0.2.5 / 10.0.2.6 Optional second, third and fourth DNS server (if any)
10.0.2.15 The emulated device's own network/ethernet interface
127.0.0.1 The emulated device's own loopback interface
basically if you run your server locally you should try and hit 10.0.2.2 address
from the emulator ---
Cheers,

Related

I am trying to send data from Browser to Android mobile App using STOMP and is facing issue with IP address

I am pretty new to STOMP, just learning it for a few weeks only. I have been trying for some time to send data from Browser to Android mobile App using STOMP, so far I have been successful in sending data from my browser to Android emulator, however if I try it on my mobile phone, the app will crash.
What I did:
I ran the Spring Boot Websocket Server before running the Android studio emulator
Used the same wifi for my phone and laptop where the server is run on.
My code is based off of xlui/WebSocketExample. (Search on google and you can find the code)
I am using NaikSoftware/StompProtocolAndroid in Android Studio, the Android client uses StompProtocolAndroid which implements protocol STOMP on Android, to subscribe or send message to server.
The Spring Boot WebSocket Server is ran on Intelliji full Version.
changed from 10.0.2.2/8080/im/websocket to Stomp.over(Stomp.ConnectionProvider.OKHTTP, "ws://MY LAPTOP IP ADDRESS/8080/im/websocket");
My Code in Android Studio for the Broadcast activity:
package app.xlui.example.im.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import app.xlui.example.im.R;
import app.xlui.example.im.conf.Const;
import app.xlui.example.im.util.StompUtils;
import ua.naiksoftware.stomp.Stomp;
import ua.naiksoftware.stomp.StompClient;
import ua.naiksoftware.stomp.dto.StompCommand;
import ua.naiksoftware.stomp.dto.StompHeader;
import ua.naiksoftware.stomp.dto.StompMessage;
#SuppressWarnings({"FieldCanBeLocal", "ResultOfMethodCallIgnored", "CheckResult"})
public class BroadcastActivity extends AppCompatActivity {
private Button broadcastButton;
private Button groupButton;
private Button chatButton;
private EditText nameText;
private Button sendButton;
private TextView resultText;
private EditText nameput;
private void init() {
broadcastButton = findViewById(R.id.broadcast);
broadcastButton.setEnabled(false);
groupButton = findViewById(R.id.groups);
chatButton = findViewById(R.id.chat);
nameText = findViewById(R.id.name);
sendButton = findViewById(R.id.send);
resultText = findViewById(R.id.show);
nameput=findViewById(R.id.name2);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast);
this.init();
StompClient stompClient = Stomp.over(Stomp.ConnectionProvider.OKHTTP, "ws://MY LAPTOP IP ADDRESS/im/websocket");
StompUtils.lifecycle(stompClient);
Toast.makeText(this, "Start connecting to server", Toast.LENGTH_SHORT).show();
// Connect to WebSocket server
stompClient.connect();
// 订阅消息
Log.i(Const.TAG, "Subscribe broadcast endpoint to receive response");
stompClient.topic(Const.broadcastResponse).subscribe(stompMessage -> {
JSONObject jsonObject = new JSONObject(stompMessage.getPayload());
Log.i(Const.TAG, "Receive: " + stompMessage.getPayload());
runOnUiThread(() -> {
try {
resultText.append(jsonObject.getString("response") + "\n");
nameput.setText(jsonObject.getString("response"));
} catch (JSONException e) {
e.printStackTrace();
}
});
});
sendButton.setOnClickListener(v -> {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", nameText.getText());
} catch (JSONException e) {
e.printStackTrace();
}
stompClient.send(new StompMessage(
// Stomp command
StompCommand.SEND,
// Stomp Headers, Send Headers with STOMP
// the first header is required, and the other can be customized by ourselves
Arrays.asList(
new StompHeader(StompHeader.DESTINATION, Const.broadcast),
new StompHeader("authorization", "this is a token generated by your code!")
),
// Stomp payload
jsonObject.toString())
).subscribe();
nameText.setText("");
});
groupButton.setOnClickListener(v -> {
Intent intent = new Intent();
intent.setClass(BroadcastActivity.this, GroupActivity.class);
startActivity(intent);
this.finish();
});
chatButton.setOnClickListener(v -> {
Intent intent = new Intent();
intent.setClass(BroadcastActivity.this, ChatActivity.class);
startActivity(intent);
this.finish();
});
}
}
My Code in Android Studio for the Const activity:
public class Const {
public static final String TAG = "xlui";
public static final String placeholder = "placeholder";
/**
* <code>im</code> in address is the endpoint configured in server.
* If you are using AVD provided by Android Studio, you should uncomment the upper address.
* If you are using Genymotion, nothing else to do.
* If you are using your own phone, just change the server address and port.
*/
private static final String address = "ws://10.0.2.2:8080/im/websocket";//for android vm
//public static final String address = "ws://10.0.3.2:8080/im/websocket";//for Genymotion
public static final String broadcast = "/broadcast";
public static final String broadcastResponse = "/b";
// replace {#code placeholder} with group id
public static final String group = "/group/" + placeholder;
public static final String groupResponse = "/g/" + placeholder;
public static final String chat = "/chat";
// replace {#code placeholder} with user id
public static final String chatResponse = "/user/" + placeholder + "/msg";
}
My Code in Android Studio for the StompUtils activity:
import android.util.Log;
import app.xlui.example.im.conf.Const;
import ua.naiksoftware.stomp.StompClient;
import static app.xlui.example.im.conf.Const.TAG;
public class StompUtils {
#SuppressWarnings({"ResultOfMethodCallIgnored", "CheckResult"})
public static void lifecycle(StompClient stompClient) {
stompClient.lifecycle().subscribe(lifecycleEvent -> {
switch (lifecycleEvent.getType()) {
case OPENED:
Log.d(TAG, "Stomp connection opened");
break;
case ERROR:
Log.e(TAG, "Error", lifecycleEvent.getException());
break;
case CLOSED:
Log.d(TAG, "Stomp connection closed");
break;
}
});
}
}
I do not know what I did wrong, I you have any suggestions please do say.

On a Sunmi K2 Terminal how can I print (on the build-in printer) something using WinDev Mobile?

I'm using a Sunmi K2 POS Checkout Terminal running with Android 7.1.2
I'm developing a POS software with WinDev for Mobile 26, I'm already displaying some windows, now the question is, how can I print on the build-in pos printer??
There is a print-test app on the kiosk installed, this works fine.
In the settings there is a printer settings too, but this says "no device installed"...
In the documentation there is a "AIDL interface" mentioned...
And more, there is a API sample written:
Bound Service
Intent intent = new Intent();
intent.setPackage("com.sunmi.extprinterservice");
intent.setAction("com.sunmi.extprinterservice.PrinterService");
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
It is necessary to establish a new ServiceConnection service to bind the callback
ServiceConnection serviceConnection = new ServiceConnection() {
#Override public void onServiceConnected(ComponentName name, IBinder service) {
ExtPrinterService ext = ExtPrinterService.Stub.asInterface(service);
}
#Override public void onServiceDisconnected(ComponentName name) { }
};
Use ext object to realize one’s own printing task
ext.printText(“123456\n”);
Unbind the service after the completion of the usage
unbindService(serviceConnection);
Question is, how can I use this Java code in WinDev Mobile??
EDIT:
I managed to print to the printer, but there is a small bug, so sometime it doesn't start immediatly, so therefore is the loop...
import android.content.ComponentName;
import android.content.Context;
import static android.content.Context.BIND_AUTO_CREATE;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.widget.Toast;
import com.sunmi.extprinterservice.ExtPrinterService;
public static void PrintToSunmiPrinter(byte[] cmd) {
getCurrentActivity();
Context context = getApplicationContext();
ExtPrinterService ext;
ServiceConnection serviceConnection = new ServiceConnection() {
#Override public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
try {
ExtPrinterService ext = ExtPrinterService.Stub.asInterface(service);
int ret_code;
int zz=0;
ret_code=ext.printerInit();
while(ret_code==-1){
zz++;
if (zz>100) { Toast.makeText(context, "ERROR! / "+ret_code, Toast.LENGTH_SHORT).show(); break; }
ret_code=ext.printerInit();
}
ext.sendRawData(cmd);
ext.cutPaper(1, 0);
ext.flush();
} catch(Exception ex){
Toast.makeText(getApplicationContext(), "ERROR! "+ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
}
};
Intent intent = new Intent();
intent.setPackage("com.sunmi.extprinterservice");
intent.setAction("com.sunmi.extprinterservice.PrinterService");
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}

Android signal to Arduino bluetooth shell

My team and I are currently trying to get our android app to send a signal to our arduino with a bluetooth shell on it. The signal doesn't need to be meaningful in anyway only that the arduino knows a signal has been sent. I have seen allot of online material on this, but none of it seems to coincide and none of it seems to work for me.
My current code: (we only want to send a signal when onRecieve() is called)
package com.example.alarmquiz2;
import android.provider.Settings.Secure;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.UUID;
import android.telephony.TelephonyManager;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
import android.bluetooth.BluetoothClass.Device;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.widget.Toast;
import android.content.Intent;
import android.content.BroadcastReceiver;
public class AlarmReceiver
extends BroadcastReceiver
{
Sound s = new Sound();
private BluetoothAdapter blue;
private Context contexxt;
private Device arduino;
private BluetoothSocket btSocket;
private TelephonyManager tManager;
private UUID uuid;
private OutputStream outStream;
private InputStream inStream;
private static String address = "00:14:03:18:42:19";
public void onReceive(Context context, Intent intent)
{
TelephonyManager tManager =
(TelephonyManager)context
.getSystemService(Context.TELEPHONY_SERVICE);
uuid = UUID.fromString(tmanager.getDeviceID());
contexxt = context;
this.CheckBt();
this.Connect();
this.writeData("meh");
if (!s.isPlaying())
{
s.setSound(context);
s.startSound();
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
else if (s.isPlaying())
{
s.stopSound();
Intent i = new Intent(context, SecondscreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
private void CheckBt()
{
blue = BluetoothAdapter.getDefaultAdapter();
if (!blue.isEnabled())
{
Toast
.makeText(contexxt, "Bluetooth Disabled !", Toast.LENGTH_SHORT)
.show();
/*
* It tests if the bluetooth is enabled or not, if not the app will
* show a message.
*/
}
if (blue == null)
{
Toast.makeText(contexxt, "Bluetooth null !", Toast.LENGTH_SHORT)
.show();
}
}
public void Connect()
{
BluetoothDevice device = blue.getRemoteDevice(address);
Log.d("", "Connecting to ... " + device);
blue.cancelDiscovery();
try
{
btSocket = device.createRfcommSocketToServiceRecord(uuid);
/*
* Here is the part the connection is made, by asking the device to create a
* RfcommSocket (Unsecure socket I guess), It map a port for us or something
* like that
*/
btSocket.connect();
Log.d("", "Connection made.");
}
catch (IOException e)
{
try
{
btSocket.close();
}
catch (IOException e2)
{
Log.d("", "Unable to end the connection");
}
Log.d("", "Socket creation failed");
}
/*
* this is a method used to read what the Arduino says for example when
* you write Serial.print("Hello world.") in your Arduino code
*/
}
private void writeData(String data)
{
try
{
outStream = btSocket.getOutputStream();
}
catch (IOException e)
{
Log.d("", "Bug BEFORE Sending stuff", e);
}
String message = data;
/* In my example, I put a button that invoke this method and send a string to it */
byte[] msgBuffer = message.getBytes();
try
{
outStream.write(msgBuffer);
}
catch (IOException e)
{
Log.d("", "Bug while sending stuff", e);
}
}
}
Ive also give myself all the required permissions in my manifest. The problem I am presently getting on my friends phone is that the "getDeviceID()" is returning a 14 digit number as opposed to the "00000000-0000-0000-0000-000000000000" format. Any suggestions, scoldings, or advice would be most welcome.
This:
uuid = UUID.fromString(tmanager.getDeviceID());
...
btSocket = device.createRfcommSocketToServiceRecord(uuid);
is most certainly not what you want to do.
What makes you think that the "device ID" of the phone(?) is in some way related to the UUID which is used to identify a certain bluetooth service at the other device?
Btw, did you read the docs?
You definitely need to find out which UUID you have to use to connect to the specific service the destination device provides on its BT interface. A list of well-known, standard UUIDs can be found here for example.
Many devices provide the "serial port profile" (SPP) for basic, stream-oriented data exchange. You may want to try that first.
Here's another source which may help.

Bluetooth discovery of all services with a specific UUID

Can an Android application get the list of available sockets on a remote device which are SDP registered to a specific UUID? I can see how to connect to a single socket with the given UUID, but I cannot find a way to iterate through all the sockets which share that UUID.
I know my code is crap. I know I'm not supposed to do blocking operations in the Activity, and that everything here is completely hacky. I'm only trying to get a proof of concept running before I architect this correctly.
That said, here's my code. I took an approach which isn't working.
package {intentionally removed};
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private String MY_TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast error = Toast.makeText(getApplicationContext(), "Enable BT and try again", Toast.LENGTH_LONG);
error.show();
Log.e(MY_TAG, "BT not enabled. Quitting.");
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
Log.i(MY_TAG, "Found " + pairedDevices.size() + " bonded devices");
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
int i = 1;
while (true) {
Log.i(MY_TAG, "Device " + device.getAddress() + " with name " + device.getName());
//Repeatedly try to connect to the SDP UUID; move to the next device when this fails.
BluetoothSocket s = null;
try {
s = device.createRfcommSocketToServiceRecord(UUID.fromString("{intentionally removed}"));
Thread.sleep(1000);
try{
s.connect();
}
catch (Exception e) {
Log.i(MY_TAG, "could not connect to socket.");
break;
}
Log.i(MY_TAG, "Connected to a socket! Whee! " + i + " found.");
InputStream is = s.getInputStream();
Log.i(MY_TAG, "got the stream");
while (true) {
Log.i(MY_TAG, "began read loop");
int j = -1;
try {
j = is.read();
}
catch (Exception e)
{
//RESUME NEXT...mwahahaha
}
if (j == -1) {
Log.i(MY_TAG, "ran out of ibytes");
break;
}
Log.i(MY_TAG, "ibyte: " + is.read());
}
i++;
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(MY_TAG, "Unable to connect.", e);
break;
}
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
}
(the UUID I pulled because I'd rather not reveal what I'm up to. It's someone else's.)
I know there to be multiple sockets serving the same UUID on the other end. The code I've just given tries to connect to each socket, forcing createRfcommSocketToServiceRecord to grab another socket. However, one of the sockets I am unable to connect to...leaving me no way to iterate to the next one (as createRfcommSocketToServiceRecord just returns the same socket next iteration).
Is there a saner way to do this? I want a nice function I can call which lists out all of the sockets I can connect to with a given UUID. Does such a thing exist?
Thanks
Yes, it exists. How it works:
You create a class i.e. GattAttributes that includes known UUIDs.
Discover Services and Characteristics in your Service class
Loop through the discovered Services and Characteristics in your Activity (optionally, you can populate a list for the user to see)
This gives you the available Services and Characteristics in a list.
Look at this Google Bluetooth LE example to see the code.
The example lets user choose the Characteristic, but if you want to connect to the concrete Characteristic, that you know beforehand (as I did):
In your Service class, within onServicesDiscovered put:
BluetoothGattCharacteristic characteristic = gatt.getService(SERVICE_UUID).getCharacteristic(CHARACTERISTIC_UUID);
If you want to also add notifications and utilize onCharacteristicChanged(), use this code:
// Enable notifications for this characteristic locally
gatt.setCharacteristicNotification(characteristic, true);
// Write on the config descriptor to be notified when the value changes
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
CLIENT_CHARACTERISTIC_CONFIG needs to be defined, see the Google code referenced above.

VB.Net Server & Android Client (Socket) Send & Receive

I am new to Android programming I wrote a simple Server(VB.NET) / Client(Java/Android) program. Text from Android/Java is send successfully to VB.Net but Response from VB.Net is not received in Android/Java (buffer.readLine() returns null)
Am I missing something?
Here are my Codes
VB.NET (Server)
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim server As New TcpListener(9999)
Dim client As New TcpClient
Dim stream As NetworkStream
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Start_Click(sender As Object, e As EventArgs) Handles Start.Click
Me.Text = "Waiting...."
Dim str As String
server.Start()
client = server.AcceptTcpClient
stream = client.GetStream()
Dim r_byt(client.ReceiveBufferSize) As Byte
stream.Read(r_byt, 0, client.ReceiveBufferSize)
Str = Encoding.ASCII.GetString(r_byt)
Label1.Text = str
End Sub
Private Sub Responce_Click(sender As Object, e As EventArgs) Handles Responce.Click
Dim s_byt() As Byte = Encoding.ASCII.GetBytes("Got it" & vbCr)
stream.Write(s_byt, 0, s_byt.Length)
stream.Flush()
stream.Close()
client.Close()
server.Stop()
End Sub
Android/Java(Client)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
Button buttonSend, buttonReceive;
private static Socket socket = null;
PrintStream stream = null;
BufferedReader buffer = null;
String string = "a";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
socket = new Socket("192.168.0.104", 9999);
stream = new PrintStream(socket.getOutputStream());
stream.println("Hi Server...");
buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
string = buffer.readLine();
Log.d("ServerActivity", " - " + string);
buffer.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
It looks like you have a couple of issues:
In the server side, you are trying to read something from the socket
into r_byt, and you are not writing anything to it on cliente side.
When you press the send button on server side, r_byt still null and
that's what you receive on cliente side.
On client side the call to socket read is blocking and after a few
seconds will result in a ANR error (Application not Responding) in
the cliente. You should move the socket read to a different thread
from the UI. The newer Android versions don't even let you read from
a socket in the UI thread.
Regards.

Categories