again i have got a problem with socket programming in Android. My Problem is Selector.select() returns zero that there are no SocketChannels ready for writing. And again the same code works in normal Java but does not work in Android. Here is my code:
package com.test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class WebSocketTest extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SocketChannel channel = null;
SocketAddress socketAdress = new InetSocketAddress("10.0.0.1", 8787);
try {
channel = SocketChannel.open();
} catch (IOException e) {
Log.e("ERROR", "channel open");
}
try {
channel.configureBlocking(false);
} catch (IOException e1) {
Log.e("ERROR", "channel blocking");
}
try {
channel.connect(socketAdress);
} catch (IOException e) {
Log.e("ERROR", "channel connect");
}
try {
while(!channel.finishConnect())
{
}
} catch (IOException e1) {
Log.e("ERROR", "channel finishConnect");
}
Selector selector = null;
try {
selector = Selector.open();
} catch (IOException e) {
Log.e("ERROR", "selector open");
}
try {
channel.register(selector, channel.validOps());
} catch (ClosedChannelException e) {
Log.e("ERROR", "channel register");
}
boolean i = true;
while(i)
{
int readyChannels = 0;
try {
readyChannels = selector.select();
} catch (IOException e) {
Log.e("ERROR", "selector select");
}
if(readyChannels > 0)
{
i = false;
}
}
}
}
In Java readyChannels = 1. In Android it is 0.
Can anyone help me?
Emulator sits behind a virtual router. You need to configure Network Redirections (port forwarding) to make a certain port on emulator visible to the outside network (including your computer).
There are several issues with this NIO code.
Instead of connecting and then spinning around finishConnect(), possibly forever, you should connect before going into non-blocking mode. At the moment you're just burning the CPU, flattening the battery, etc.
You should only register OP_WRITE when you have something to write. It is normally 'ready', so if you register the channel for it permanently your selection loop will just spin. The only time OP_WRITE isn't ready is when you have filled the socket send buffer.
Related
I've been following these two posts SPP Server and Client and this stackoverflow post. I have the server running on a Linux VM and the Android app running on a Samsung Galaxy S6. When I run the server code in Intellij, it says:
"Server Started. Waiting for clients to connect".
When I run the Android app, I get the following Alert box saying:
"Fatal Error. In OnResume()and an exception occurred during write: socket closed.
Check that the SPP UUID: 00001101-0000-1000-8000-00805F9B34FB exists on server. Press OK to exit.
Why is this happening and how can I resolve it so the server will connect and receive a string from the Android app?
SPP Server Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.bluetooth.*;
import javax.microedition.io.*;
public class SampleSPPServer {
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("0000110100001000800000805F9B34FB", false);
//Create the servicve url
String connectionString = “btspp://localhost:” + uuid +”;name=Sample
SPP Server”;
//open server url
StreamConnectionNotifier streamConnNotifier =
(StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println(“\nServer Started. Waiting for clients to connect…”);
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println(“Remote device address: “+dev.getBluetoothAddress());
System.out.println(“Remote device name: “+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new
InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write(“Response String from SPP Server\r\n”);
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println(“Address: “+localDevice.getBluetoothAddress());
System.out.println(“Name: “+localDevice.getFriendlyName());
SampleSPPServer sampleSPPServer=new SampleSPPServer();
sampleSPPServer.startServer();
}
}
Android Client Code:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.UUID;
public class BluetoothClient extends AppCompatActivity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your server's MAC address
private static String address = "00:10:60:AA:B9:B2";
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_client);
out = (TextView) findViewById(R.id.out);
out.append("\n...In onCreate()...");
btAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBTState();
}
public void onStart() {
super.onStart();
out.append("\n...In onStart()...");
}
public void onResume() {
super.onResume();
out.append("\n...In onResume...\n...Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
try {
btSocket.connect();
out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");
String message = "Hello from Android.\n";
out.append("\n\n...The message that we will send to the server is: "+message);
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
AlertBox("Fatal Error", msg);
}
}
public void onPause() {
super.onPause();
//out.append("\n...Hello\n");
InputStream inStream;
try {
inStream = btSocket.getInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
out.append("\n..."+lineRead+"\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.append("\n...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
public void onStop() {
super.onStop();
out.append("\n...In onStop()...");
}
public void onDestroy() {
super.onDestroy();
out.append("\n...In onDestroy()...");
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
out.append("\n...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
public void AlertBox( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message + " Press OK to exit." )
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).show();
}
}
Android Studio Logcat:
android.view.WindowLeaked: Activity com.example.toby.btclientapp.BluetoothClient has leaked window com.android.internal.policy.PhoneWindow$DecorView{b73d40d V.E...... R.....I. 0,0-1368,1249} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:569)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.example.toby.btclientapp.BluetoothClient.AlertBox(BluetoothClient.java:181)
at com.example.toby.btclientapp.BluetoothClient.onResume(BluetoothClient.java:107)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
at android.app.Activity.performResume(Activity.java:6987)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4145)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4250)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3361)
at android.app.ActivityThread.access$1100(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
07-26 13:09:21.574 3857-3857/? E/WindowManager: android.view.WindowLeaked: Activity com.example.toby.btclientapp.BluetoothClient has leaked window com.android.internal.policy.PhoneWindow$DecorView{9723488 V.E...... R....... 0,0-1368,1249} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:569)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.example.toby.btclientapp.BluetoothClient.AlertBox(BluetoothClient.java:181)
at com.example.toby.btclientapp.BluetoothClient.onResume(BluetoothClient.java:107)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
at android.app.Activity.performResume(Activity.java:6987)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4145)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4250)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
07-26 13:09:21.574 3857-3857/? E/WindowManager: android.view.WindowLeaked: Activity com.example.toby.btclientapp.BluetoothClient has leaked window com.android.internal.policy.PhoneWindow$DecorView{cea821b V.E...... R....... 0,0-1368,799} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:569)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.example.toby.btclientapp.BluetoothClient.AlertBox(BluetoothClient.java:181)
at com.example.toby.btclientapp.BluetoothClient.onPause(BluetoothClient.java:135)
at android.app.Activity.performPause(Activity.java:7033)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1339)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4577)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4550)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4525)
at android.app.ActivityThread.access$1300(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1813)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I needed to change the MAC address of the Bluetooth adapter. It works now.
I have barcode scanner who should work with my app. It is supposed to run in the background and my app is responding to input coming from the scanner in its own way. However it should not be used as a hardware keyboard and its input not directed to the firstresponder (no text entries i.e.). Currently i'm stuck with it although i know i have done a solution like described before (couple years ago for a company).
The first part of the question is now how to prevent the bluetooth device from being attached as a hardware keyboard? Can i control this behaviour or is it maybe some mode or setting that the bluetooth device must support (if yes is there name for it to check in the specifications)?
I guess if the device is not attached as a bluetooth keyboard i could establish a connection and listen to the bluetooth socket input stream for available bytes and collect them. Currently i cannot establish a connection because
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
throws an java.io.IOException with message read failed, socket might closed or timeout, read ret: -1. Any ideas why i cannot connect to the socket, although the device is currently paired to my device?
EDIT:
Because it was asked, the complete connection source code
private void initBluetooth() {
BTAdapter = BluetoothAdapter.getDefaultAdapter();
if (BTAdapter == null) {
Log.e(getClass().getName(), "no BT Adapter");
return;
}
if (!BTAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQUEST_BLUETOOTH);
return;
}
listDevices();
}
private void listDevices() {
Set<BluetoothDevice> pairedDevices = BTAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
Log.d(getClass().getName(), String.format("Device found %s", device.getName()));
if(device.getName().indexOf("Barcode") > 0) {
mmDevice = device;
try {
openBT();
} catch(IOException e) {
Log.e(getClass().getName(), "Failed", e);
}
break;
}
}
}
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
//now make the socket connection in separate thread
Thread connectionThread = new Thread(new Runnable() {
#Override
public void run() {
// Always cancel discovery because it will slow down a connection
BTAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
//connection to device failed so close the socket
e.printStackTrace();
try {
mmSocket.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
});
connectionThread.start();
mmInputStream = mmSocket.getInputStream();
}
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.
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.
Im trying to write a program using sockets having an android phone as the client and my PC as the server i found and slightly modified code for both sides and my server code works but i can't get the client activity to and i don't know acutally how to get the to programs to talk i want to basically be able to have either side input text and have it sent and set visable to the other i know how much of a stickler you guys are for questions so... How do i get these to communicate?
Client code (The emulator crashes before i can even begin to see the problem)
package com.example.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.*;
import java.net.*;
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener((android.view.View.OnClickListener) connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 9999);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
the Server code
import java.io.*;
import java.net.*;
/**
* Simple server using Java Sockets.
* #author Jonathan Engelsma (http://www.cis.gvsu.edu/~engelsma)
*
*/
public class Server {
/**
* #param args
*/
public static void main(String[] args) {
try {
// First we create a server socket and bind it to port 9999.
ServerSocket myServerSocket = new ServerSocket(9999);
// wait for an incoming connection...
System.out.println("Server is waiting for an incoming connection on host="
+ InetAddress.getLocalHost().getCanonicalHostName()
+ " port=" + myServerSocket.getLocalPort());
Socket skt = myServerSocket.accept();
// ok, got a connection. Let's use java.io.* niceties to read and write from the connection.
BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintStream myOutput = new PrintStream(skt.getOutputStream());
// attempt to read input from the stream.
String buf = myInput.readLine();
// if we got input, print it out and write a message back to the remote client..
if (buf != null) {
System.out.println("Server read: [" + buf + "]");
myOutput.print("got it");
}
// close the connection.
skt.close();
System.out.println("Server is exiting");
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("Whoops, something bad happened! I'm outta here.");
}
}
}
Are you using
<uses-permission android:name="android.permission.INTERNET" />
In the Android Manifest? That could cause your problem.
if you are using ICS or JB, then you are probably being restricted from opening network connections from within your main activity. you will get an opaque error message regarding network permissions.
i cant repost my answer to another quite similar StackOverflow question here (it is considered spamming by moderators), but you can CHECK IT OUT HERE.
i posted a functional send and receive socket connector client using asynctask there.