here's my full code: the cnx is established , and i am sending data to server , but i cant read anything from the server...
public class client extends Activity
{
/** Called when the activity is first created. */
Socket sock;
String spliter = "**";
String mobileNbr = "100";
String LastJOKEId = "-1";
String spliterlast = "^^$$";
BufferedReader inFromServer;
DataOutputStream outToServer;
TextView cnx;
TextView output;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupNetworking();
// Thread readerThread=new Thread(new IncomingReader());
// readerThread.start();
}
private void setupNetworking()
{
try
{
Log.i("ClientActivity", "Connecting...");
sock = new Socket("192.168.153.221", 9003);
cnx = (TextView) findViewById(R.id.textView1);
cnx.setText("Network Established.");
inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Log.i("ClientActivity", "Sending command.");
outToServer = new DataOutputStream(sock.getOutputStream());
String sentence = "logins" + spliter + mobileNbr + spliter + LastJOKEId + spliterlast;
outToServer.writeBytes(sentence + '\n');
Log.i("ClientActivity", "Sent.");
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
cnx = (TextView) findViewById(R.id.textView1);
cnx.setText("Network failed");
e.printStackTrace();
}
}
public class IncomingReader implements Runnable
{
String message;
public void run()
{
try
{
while ((message = inFromServer.readLine()) != null)
{
output = (TextView) findViewById(R.id.textView2);
output.setText(message);
}
}
catch (IOException e)
{
output = (TextView) findViewById(R.id.textView2);
output.setText("nth to display");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package some;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class NetClient {
/**
* Maximum size of buffer
*/
public static final int BUFFER_SIZE = 2048;
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private String host = null;
private String macAddress = null;
private int port = 7999;
/**
* Constructor with Host, Port and MAC Address
* #param host
* #param port
* #param macAddress
*/
public NetClient(String host, int port, String macAddress) {
this.host = host;
this.port = port;
this.macAddress = macAddress;
}
private void connectWithServer() {
try {
if (socket == null) {
socket = new Socket(this.host, this.port);
out = new PrintWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void disConnectWithServer() {
if (socket != null) {
if (socket.isConnected()) {
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void sendDataWithString(String message) {
if (message != null) {
connectWithServer();
out.write(message);
out.flush();
}
}
public String receiveDataFromServer() {
try {
String message = "";
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = in.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
}
disConnectWithServer(); // disconnect server
return message;
} catch (IOException e) {
return "Error receiving response: " + e.getMessage();
}
}
}
//---------------------------Use NetClient------------------------------------------------
NetClient nc = new NetClient(host, port, mac); //mac address maybe not for you
nc.sendDataWithString("your data");
String r = nc.receiveDataFromServer();
This is our android socket client works fine with Python server socket, Hope it will help you.
HttpResponse response = m_httpClient.execute( request );
String result = "";
if( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK )
{
// open stream
InputStream stream = response.getEntity().getContent();
if( stream != null )
{
int len = 0;
byte[] buf = new byte[ 1024 ];
try
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while( ( len = stream.read( buf ) ) > 0 )
{
outputStream.write( buf, 0, len );
}
buf = outputStream.toByteArray();
result = EncodingUtils.getAsciiString( buf );
}
catch( IOException e )
{
e.printStackTrace();
}
finally
{
stream.close();
}
}
Related
I'm working in a remote ScreenRecord in real time based in this code.
With this code of reference i'm able to record screen of my smartphone with success and saving .mp4 file in some folder previous defined.
But to my project, i need that this content be sent to server (similar to Team View for android).
My last attempt to sent this content to server side was like this:
OutputStream os = clientSocket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream (os);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(encodedData);
oos.flush();
bos.flush();
os.flush();
Reference => this question
but comes a error of:
java.io.NotSerializableException
in this line > oos.writeObject(encodedData);
Then, i want know how solve it or some other way to make this task.
Here is complete code:
/////////////////////////////////////// CLIENTSOCKET ///////////////////////////////////////////
Socket clientSocket;
int SERVERPORT = 60;
String SERVER_IP = "192.168.15.6";
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
clientSocket = new Socket(serverAddr, SERVERPORT);
new Thread(new CommsThread()).start();
} catch (Exception e1) {
System.out.println(e1.toString());
}
}
}
class CommsThread implements Runnable {
#Override
public void run() {
try {
System.out.println("Waiting for server request");
while(clientSocket.isConnected()){
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true);
if (reader.ready()) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
if(line != null && !line.trim().isEmpty()) {
if(line.equalsIgnoreCase("screenrecord")){
System.out.println(out.toString());
mMediaProjectionManager = (MediaProjectionManager)getSystemService(android.content.Context.MEDIA_PROJECTION_SERVICE);
Intent permissionIntent = mMediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(permissionIntent, REQUEST_CODE_CAPTURE_PERM);
out.flush();
}
if(line.equalsIgnoreCase("exit")) {
stopRecording();
break;
}
}
}
}
Thread.sleep(100);
}
System.out.println("Shutting down Socket!!");
clientSocket.close();
} catch (Exception e1) {
System.out.println(e1.toString());
}
}
}
////////////////////////////////////// MEDIAPROJECTION /////////////////////////////////////////
private static final int REQUEST_CODE_CAPTURE_PERM = 1234;
private static final String VIDEO_MIME_TYPE = "video/avc";
int VIDEO_WIDTH, VIDEO_HEIGHT;
private boolean mMuxerStarted = false;
private MediaProjectionManager mMediaProjectionManager;
private MediaProjection mMediaProjection;
private Surface mInputSurface;
private MediaMuxer mMuxer;
private MediaCodec mVideoEncoder;
private MediaCodec.BufferInfo mVideoBufferInfo;
private int mTrackIndex = -1;
private final Handler mDrainHandler = new Handler(Looper.getMainLooper());
private Runnable mDrainEncoderRunnable = new Runnable() {
#Override
public void run() {
drainEncoder();
}
};
public void stopRecording(){
releaseEncoders();
}
private void startRecording() {
DisplayManager dm = (DisplayManager)getSystemService(Context.DISPLAY_SERVICE);
Display defaultDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY);
if (defaultDisplay == null) {
throw new RuntimeException("No display found.");
}
DisplayMetrics metrics = getResources().getDisplayMetrics();
int screenWidth = metrics.widthPixels;
int screenHeight = metrics.heightPixels;
int screenDensity = metrics.densityDpi;
VIDEO_WIDTH = screenWidth;
VIDEO_HEIGHT = screenHeight;
prepareVideoEncoder();
mMediaProjection.createVirtualDisplay("Recording Display", screenWidth, screenHeight, screenDensity, 0, mInputSurface, null, null);
drainEncoder();
}
private void prepareVideoEncoder() {
mVideoBufferInfo = new MediaCodec.BufferInfo();
MediaFormat format = MediaFormat.createVideoFormat(VIDEO_MIME_TYPE, VIDEO_WIDTH, VIDEO_HEIGHT);
int frameRate = 30;
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, 6000000);
format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate);
format.setInteger(MediaFormat.KEY_CAPTURE_RATE, frameRate);
format.setInteger(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, 1000000 / frameRate);
format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
try {
mVideoEncoder = MediaCodec.createEncoderByType(VIDEO_MIME_TYPE);
mVideoEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mInputSurface = mVideoEncoder.createInputSurface();
mVideoEncoder.start();
} catch (IOException e) {
releaseEncoders();
}
}
private boolean drainEncoder() {
mDrainHandler.removeCallbacks(mDrainEncoderRunnable);
while (true) {
int bufferIndex = mVideoEncoder.dequeueOutputBuffer(mVideoBufferInfo, 0);
if (bufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
break;
} else if (bufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
} else if (bufferIndex < 0) {
} else {
ByteBuffer encodedData = mVideoEncoder.getOutputBuffer(bufferIndex);
if (encodedData == null) {
throw new RuntimeException("couldn't fetch buffer at index " + bufferIndex);
}
if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
mVideoBufferInfo.size = 0;
}
if (mVideoBufferInfo.size != 0) {
encodedData.position(mVideoBufferInfo.offset);
encodedData.limit(mVideoBufferInfo.offset + mVideoBufferInfo.size);
try {
OutputStream os = clientSocket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream (os);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(encodedData);
oos.flush();
bos.flush();
os.flush();
} catch (IOException e) {
throw new RuntimeException("couldn't send data to server");
}
} else {
}
mVideoEncoder.releaseOutputBuffer(bufferIndex, false);
}
if ((mVideoBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
break;
}
}
mDrainHandler.postDelayed(mDrainEncoderRunnable, 10);
return false;
}
private void releaseEncoders() {
mDrainHandler.removeCallbacks(mDrainEncoderRunnable);
if (mMuxer != null) {
if (mMuxerStarted) {
mMuxer.stop();
}
mMuxer.release();
mMuxer = null;
mMuxerStarted = false;
}
if (mVideoEncoder != null) {
mVideoEncoder.stop();
mVideoEncoder.release();
mVideoEncoder = null;
}
if (mInputSurface != null) {
mInputSurface.release();
mInputSurface = null;
}
if (mMediaProjection != null) {
mMediaProjection.stop();
mMediaProjection = null;
}
mVideoBufferInfo = null;
mDrainEncoderRunnable = null;
mTrackIndex = -1;
}
////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (REQUEST_CODE_CAPTURE_PERM == requestCode) {
if (resultCode == RESULT_OK) {
mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, intent);
startRecording();
} else {
}
}
}
I'm using socket to create http socket server on Java android application.
Send and Get headers from client and server I'm getting fast. But get when trying read http body it takes a long time... why ?
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
public void run() {
try {
runProxy();
}catch (Throwable t){
}
};
}).start();
}
private void runProxy() throws Throwable{
try {
ServerSocket ss = new ServerSocket(8080);
while (true) {
Socket s = ss.accept();
System.err.println("Client accepted");
new Thread(new TestProxy(s)).start();
}
}catch (IOException e){
}
}
TestProxy.class
public class TestProxy implements Runnable{
private Socket s, c;
private InputStream is;
private OutputStream os;
ArrayList<String> requestList;
ArrayList<String> responseList;
private BufferedReader br;
public TestProxy(Socket s) throws Throwable{
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
this.requestList = new ArrayList<String>();
this.responseList = new ArrayList<String>();
this.run();
}
public void run(){
try {
this.readRequest();
this.forwardRequest();
this.forwardResponse(); //<--- this is trouble ??!
}catch (Throwable e){
}finally {
/*try {
s.close();
c.close();
}catch (IOException e) {}*/
}
}
private void readRequest() throws Throwable{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//int lengthBody = 0;
while(true) {
String s = br.readLine();
requestList.add(s + "\r\n");
/*if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}*/
if(s == null || s.trim().length() == 0) {
break;
}
}
is.close();
}
private void forwardRequest(){
String firstSectionInProtocol = requestList.get(0); //GET http://example.com/?d=d HTTP/1.1
Pattern p = Pattern.compile("^\\w+\\s+(\\S+)");
Matcher m = p.matcher(firstSectionInProtocol);
if(m.find()) {
String URI = m.group(1); //http://example.com/?d=d
try {
URL aURL = new URL(URI);
try {
c = new Socket(aURL.getHost(), 80);
final OutputStream outToServer = c.getOutputStream();
String firstSection = "GET "+aURL.getFile()+" HTTP/1.1\r\n";
outToServer.write(firstSection.getBytes());
System.out.println(firstSection);
for(int i = 1; i < requestList.size(); i++){
outToServer.write(requestList.get(i).getBytes());
System.out.println(requestList.get(i));
}
outToServer.flush();
}catch (IOException e) {
}
}catch (MalformedURLException e){ }
}
}
private void forwardResponse() throws Throwable{
final InputStream inFromServer = c.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inFromServer));
int lengthBody = 0;
while(true) {
String s = br.readLine();
System.out.println( s + "\r\n" );
if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}
if(s.equals("")) {
break;
}
}
//
// Processing long time
//
if (lengthBody > 0) {
int read;
StringBuilder body = new StringBuilder();
while ((read = br.read()) != -1) {
body.append((char) read);
if (body.length() >= lengthBody)
break;
}
System.out.println(body.toString());
}
}
}
in the method forwardResponse(); i trying get a body response.
while(true) {
String s = br.readLine();
System.out.println( s + "\r\n" );
/*if (s.startsWith("Content-Length: ")) { // get the
// content-length
int index = s.indexOf(':') + 1;
String len = s.substring(index).trim();
lengthBody = Integer.parseInt(len);
}*/
if(s == null) {
break;
}
}
I am trying to transmit a continuous stream of data to multiple devices over a portable hotspot connection using sockets.
I am facing two problems:
The message only gets displayed to the client AFTER all the messages are displayed in msg TextView on the server end. So if I use an infinite while(true) loop instead of for(int i = 0; i < 1000; i++), in ServerSocketReplyThread, the message never gets transmitted, and the client eventually crashes
I am unable to connect another client to the server until all the messages have been transmitted to the first client.
How do I structure the code to ensure simultaneous, real-time transmission to multiple clients?
Here's what the code looks like:
I am using an activity called Transmit activity, where I am instantiating the msg Textview, which replays the sent messages, and a server object.
msg = (TextView) findViewById(R.id.server_replayed_messages);
Server server = new Server(this);
The Server class is as follows:
public class Server {
TransmitActivity activity;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
ArrayList<Socket> socketList = new ArrayList<Socket>();
public Server(TransmitActivity a) {
this.activity = a;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread =
new SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
for(int i = 0; i < 1000; i++) {
String msgReply = DateFormat.getDateTimeInstance().format(new Date());
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.flush();
message += "replayed: " + msgReply + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong in SocketServerReplyThread! " + e.toString() + "\n";
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
}
}
}
}
On the client side I have a ReceiveActivity, where I am using the following code when a "Connect" button is clicked:
Client myClient = new Client(editTextAddress.getText()
.toString(), Integer.parseInt(editTextPort
.getText().toString()), response);
myClient.execute();
The Client class is as follows:
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse = textResponse;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice: inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
Any help would be much appreciated.
Following options resulting shown error
Android App + Multicast + Tethering On + Cell Data Off
If I connected to wifi router, no errors happen. What do I wrong or is android+multicast+tethering impossible?
public class Multicast {
final static String INET_ADDR = "224.0.0.1";
final static int PORT = 8888;
private Context mContext;
public Multicast(Context context) {
mContext = context;
}
public static NetworkInterface getWlanEth() {
final String TAG = "NetworkInterface";
Enumeration<NetworkInterface> enumeration = null;
try {
enumeration = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
NetworkInterface wlan0 = null;
StringBuilder sb = new StringBuilder();
while (enumeration.hasMoreElements()) {
wlan0 = enumeration.nextElement();
sb.append(wlan0.getName() + " ");
if (wlan0.getName().equals("wlan0")) {
return wlan0;
}
}
return null;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void startMulticastServer() {
Thread sendThread = new Thread(new Runnable() {
DatagramSocket serverSocket;
#Override
public void run() {
try {
if (serverSocket == null) {
serverSocket = new DatagramSocket(null);
serverSocket.setReuseAddress(true);
serverSocket.setBroadcast(true);
serverSocket.bind(new InetSocketAddress(PORT));
serverSocket.setSoTimeout(15000);
}
for (int i = 0; i < 5; i++) {
String msg = "Sent message no " + i;
InetAddress group = InetAddress.getByName(INET_ADDR);
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, group, PORT);
serverSocket.send(msgPacket);
String TAG = "Multicast-send";
Log.i(TAG, "Socket 1 send msg: " + msg);
Thread.sleep(500);
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
sendThread.start();
}
public void startMulticastClient() {
Thread getThread = new Thread(new Runnable() {
byte[] buf = new byte[256];
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void run() {
//Acquire the MulticastLock
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifi.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
// Create a new Multicast socket (that will allow other sockets/programs
// to join it as well.
try {
MulticastSocket clientSocket = new MulticastSocket(PORT);
//Joint the Multicast group.
clientSocket.joinGroup(new InetSocketAddress(InetAddress.getByName(INET_ADDR), PORT), getWlanEth());
clientSocket.setLoopbackMode(true);
while (true) {
// Receive the information and print it.
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket);
String msg = new String(msgPacket.getData());
String TAG = "Multicast-get";
Log.i(TAG, "Socket 1 received msg: " +msgPacket.getAddress()+" : "+ InetAddress.getByName(INET_ADDR) + " : " +msg);
}
} catch (IOException ex) {
multicastLock.release();
ex.printStackTrace();
}
multicastLock.release();
}
});
getThread.start();
}
}
I'm developing an Android application which includes Bluetooth SPP Connection. The post on Receiving String from RFCOMM on PC, sent from Android really helped me.
Even my log in Eclipse says 'wrote 6 bytes out of 6' many times and then the socket gets closed. But, I want to receive (whatever I sent) in my PC using Hyperterminal. How do I do that? How to specify Virtual COM Port in code?
I'm using a Samsung SGH-T759 for testing in USB Debugging mode.
Here's my code:
public class BluetoothActivity extends Activity {
private int bluetooth = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
TextView text = (TextView) findViewById(R.id.text);
text.setText("Click on the button to access devices through Bluetooth");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_bluetooth, menu);
return true;
}
public void bluetoothActivate(View view) {
int REQUEST_ENABLE_BT = 1;
int RESULT_ENABLE_BT = 0;
//TextView text = (TextView) findViewById(R.id.text);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
System.out.println("Button clicked...");
if (mBluetoothAdapter == null) {
//txtView.setText("This device does not support Bluetooth");
CharSequence txt = "This device does not support Bluetooth";
Toast toast = Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
//CharSequence text = "Bluetooth is supported!!!";
System.out.println("Bluetooth is supported!!!");
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
onActivityResult(REQUEST_ENABLE_BT, RESULT_ENABLE_BT, enableBtIntent);
}
else
bluetooth = 1;
device_access(view);
}
}
public void device_access(View view) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
TextView text = (TextView) findViewById(R.id.text);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
Spinner btDevices = (Spinner) findViewById(R.id.btDevices);
System.out.println("Bluetooth devices...");
if (bluetooth == 1)
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
System.out.println("Bluetooth paired devices...");
final ArrayAdapter<CharSequence> mArrayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1);
ArrayAdapter<CharSequence> deviceName = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1);
mArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
deviceName.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
deviceName.add(device.getName());
}
btDevices.setVisibility(1);
btDevices.setAdapter(mArrayAdapter);
//txtView.append("\nPaired Bluetooth Devices Found...");
/*// Create a BroadcastReceiver for ACTION_FOUND
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
*/
String[] dvc = btDevices.getSelectedItem().toString().split("\n");
final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for serial connection
String mac = "90:00:4E:DC:41:9D"; //my laptop's mac adress
//mac = dvc[1];
text.append("\n Data sent to " + btDevices.getSelectedItem().toString());
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mac); //get remote device by mac, we assume these two devices are already paired
// Get a BluetoothSocket to connect with the given BluetoothDevice
BluetoothSocket socket = null;
OutputStream out = null;
InputStream inp = null;
//try {
//socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
Method m;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}catch (IOException e) {}
try {
mBluetoothAdapter.cancelDiscovery();
socket.connect();
out = socket.getOutputStream();
inp = socket.getInputStream();
//now you can use out to send output via out.write
String outputValue = "Hi...\n",inputValue;
byte[] op = outputValue.getBytes(),buffer = null;
int inpBytes;
for (int i=0; i<1000000; i++) {
out.write(op);
out.flush();
}
System.out.println("Data written!!");
/*while (true) {
try {
// Read from the InputStream
inpBytes = inp.read(buffer);
inputValue = buffer.toString();
text.append(inpBytes+ " " + inputValue);
} catch (IOException e) {
}
}*/ }catch (IOException e) {} finally {
try {
socket.close();
System.out.println("Socket closed...");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
I myself solved it. I had to use the listenUsingRfcommWithServiceRecord(NAME,SERIAL_UUID) to register my phone's SPP capability on my laptop. Then, my laptop assigned a COM port for SPP communication with my phone. Then, I specified this port in AccessPort137 (another application similar to hyperterminal and better than that in some aspects) and established communication properly. My working code follows:
package com.example.bluetoothtest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
import com.example.bluetoothtest.R;
import com.example.bluetoothtest.DynamicGraph;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class BluetoothActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.bluetoothtest.MESSAGE";
public int bluetooth = 0, mState = 0;
public boolean runThread = false;
private TextView text;
public static final UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for serial connection
public static final int STATE_DISCONNECTED = 0;
public static final int STATE_CONNECTED = 1;
public static final int MESSAGE_READ = 2;
public static final int START_INTENT = 3;
public static final int REQ_CODE_DYNAMIC = 4;
public static BluetoothAdapter mBluetoothAdapter = null;
public static BluetoothDevice device = null;
BluetoothServerSocket mmServerSocket = null;
BluetoothSocket socket = null,finalSocket = null;
OutputStream out = null;
//InputStream aStream = null;
InputStreamReader aReader = null;
BufferedReader mBufferedReader = null;
ConnectedThread con = null;
AcceptThread accept = null;
ConnectThread connect = null;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
if (con != null) {con.cancel(); con = null;}
mState = STATE_DISCONNECTED;
// Start the thread to listen on a BluetoothServerSocket
if (accept!= null) {
accept = null;
}
text = (TextView) findViewById(R.id.text);
text.setText("Click on the button to access devices through Bluetooth");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_bluetooth, menu);
return true;
}
#Override
public void onDestroy(){
super.onDestroy();
runThread = false;
}
public void bluetoothActivate(View view) {
int REQUEST_ENABLE_BT = 1;
int RESULT_ENABLE_BT = 0;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
System.out.println("Button clicked...");
if (mBluetoothAdapter == null) {
CharSequence txt = "This device does not support Bluetooth";
Toast toast = Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
System.out.println("Bluetooth is supported!!!");
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
onActivityResult(REQUEST_ENABLE_BT, RESULT_ENABLE_BT, enableBtIntent);
}
else
bluetooth = 1;
device_access(view);
}
}
public void bluetoothDisconnect(View view) {
runThread = false;
con.cancel();
//connect.cancel();
System.out.println("Connection disconnected");
text.append("\n Connection disconnected");
}
public void device_access(View view) {
System.out.println("Bluetooth devices...");
if (bluetooth == 1) {
//String mac = "F0:08:F1:36:D3:5B"; //my other phone's mac adress
String mac = "90:00:4E:DC:41:9D"; //my laptop's mac adress
//String mac = "A0:4E:04:B8:1D:62";
//mac = dvc[1];
//text.append("\n Data sent to " + btDevices.getSelectedItem().toString());
//device = mBluetoothAdapter.getRemoteDevice(mac); //get remote device by mac, we assume these two devices are already paired
//text.append("device = " + device);
text.append("\n Bluetooth started...");
System.out.println("Bluetooth Started...");
//ensureDiscoverable();
String backup_file = "dynamic_bluetooth.csv";
intent = new Intent(this, DynamicGraph.class);
intent.putExtra(EXTRA_MESSAGE, backup_file);
System.out.println("Dynamic intent about to start...");
/*connect = new ConnectThread(device);
connect.start();*/
CheckBox plotGraph = (CheckBox) findViewById(R.id.plotGraph);
if (plotGraph.isChecked())
startActivityForResult(intent,REQ_CODE_DYNAMIC);
else {
accept = new AcceptThread();
accept.start();
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
this.mmDevice = device;
BluetoothSocket tmp1 = null;
try {
tmp1 = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp1;
}
#Override
public void run() {
setName("ConnectThread");
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
System.out.println("Connected with the device");
} catch (IOException e) {
try {
mmSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
/*synchronized (PrinterService.this) {
mConnectThread = null;
}*/
//connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e("PrinterService", "close() of connect socket failed", e);
}
}
}
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
System.out.println("Device set discoverable");
text.append("\n Device set discoverable");
return;
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
/*byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);*/
//float readM = Float.parseFloat(readMessage);
System.out.println("Into handler...");
String readMessage = (String) msg.obj;
text.append("\n" + readMessage);
try{
float readM = Float.parseFloat(readMessage);
text.append(" " + readM);
}catch (NumberFormatException e) {
text.append(" - Number Format Exception!!");
e.printStackTrace();
}
break;
case START_INTENT:
System.out.println("Dynamic intent about to start...");
//startActivityForResult(intent,REQ_CODE_DYNAMIC);
break;
}
}
};
private class AcceptThread extends Thread {
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
System.out.println("Listening...");
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("SPP", SERIAL_UUID);
}catch (IOException e) {
System.out.println("Listening Failed");
}
mmServerSocket = tmp;
if (mmServerSocket != null)
System.out.println("Server socket established: tmp = " + tmp);
else
System.out.println("Server socket NOT established: tmp = " + tmp);
}
public void run() {
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
//socket = mmServerSocket.accept();
System.out.println("AcceptThread Run");
while (true) {
if ((mmServerSocket != null) && (mState != STATE_CONNECTED)) {
try {
socket = mmServerSocket.accept();
device = socket.getRemoteDevice();
} catch (IOException e) {
System.out.println("Socket not received");
break;
}
if (socket!= null) {
System.out.println("Device Address: " + device.getAddress());
runThread = true;
con = new ConnectedThread(socket);
con.start();
mState = STATE_CONNECTED;
break;
}
}
else {
System.out.println("Code incomplete. Repeat Listening");
break;
}
}
}
finally {
/*try {
con.cancel();
mmServerSocket.close();
System.out.println("Socket closed...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Server Socket close problem...");
e.printStackTrace();
} */
}
}
public void cancel() {
try {
mmServerSocket.close();
accept.start();
} catch (IOException e) {
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024],readBuffer = new byte[1024];
int bytesAvailable,readBufferPosition;
char[] readMsg = new char[8192];
/*try {
aStream = socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("InputStream problem...");
e.printStackTrace();
}*/
/*aReader = new InputStreamReader( mmInStream );
mBufferedReader = new BufferedReader( aReader );*/
String aString = "---";
System.out.println("Waiting for input...");
/*try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
System.out.println("Sleeping problem...");
e1.printStackTrace();
}*/
while (runThread) {
try {
/*aReader = new InputStreamReader( mmInStream );
mBufferedReader = new BufferedReader( aReader );
//aString = mBufferedReader.readLine();
mBufferedReader.read(readMsg);
aString = new String(readMsg);
readMsg = new char[8192];
System.out.println(aString);*/
aString = "---";
byte delimiter = 'N'; //New line
readBuffer = new byte[1024];
readBufferPosition = 0;
bytesAvailable = mmInStream.read(buffer);
boolean copied = false;
if (bytesAvailable > 0)
System.out.println(bytesAvailable + " bytes available");
else
System.out.println("Bytes not available");
for(int i=0;i<bytesAvailable;i++)
{
byte b = buffer[i];
System.out.println("Byte = "+ b);
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
aString = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
copied= true;
break;
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
/*aString = new String(buffer);
aString = aString.trim();*/
//float rx_data = Float.parseFloat(aString);
System.out.println("aString = " + aString);
/*mHandler.obtainMessage(BluetoothActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();*/
//buffer = new byte[1024];
if (copied && (aString != "---"))
mHandler.obtainMessage(BluetoothActivity.MESSAGE_READ, aString)
.sendToTarget();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("mBufferedReader problem...");
e.printStackTrace();
break;
}
}
//cancel();
/*out = socket.getOutputStream();
//now you can use out to send output via out.write
String outputValue = "Hi...\n",inputValue;
byte[] op = outputValue.getBytes(),buffer = null;
int inpBytes;
for (int i=0; i<1000000; i++) {
out.write(op);
out.flush();
}
System.out.println("Data written!!");
while (true) {
try {
// Read from the InputStream
inpBytes = inp.read(buffer);
inputValue = buffer.toString();
text.append(inpBytes+ " " + inputValue);
} catch (IOException e) {
}
} */
}
public void cancel() {
try {
/*aReader.close();
mBufferedReader.close();*/
runThread = false;
mState = STATE_DISCONNECTED;
mmSocket.close();
mmServerSocket.close();
System.out.println("Socket closed in thread...");
accept = new AcceptThread();
accept.start();
} catch (IOException e) {
System.out.println("Socket close problem...");
}
}
}
}
Uncomment and run the ConnectThread also if you want bi-directional communication. I only had to receive values; so, I've commented it out. But, this thread has to be run in order to establish a COM port for your phone with your laptop. This is because, only when an application like this which uses Bluetooth SPP is run in the phone and tries to pair with the laptop (using this ConnectThread), the laptop will register the SPP capability of the phone. To see this and enable SPP from your laptop's side, do the following:
Right-click on your Bluetooth icon in the taskbar and click on 'Show Bluetooth Devices'.
In the window that opens, find your phone (remember that it must already be paired with your laptop before even running this SPP application), right-click it and go to 'Properties'.
Go to the 'Services' tab and you'll find a new entry called by the name that you provide as the first parameter in the listenUsingRfcommWithServiceRecord() method. For me it's 'SPP'.
Check that new service to enable SPP between your laptop and your phone.
Now, if you check the 'Hardware' tab, a COM port will be specified which you can use in HyperTerminal or any such application and start communicating.
Also, remember that this is NOT possible with Windows 8 yet! Whatever I've mentioned here pertains to Windows 7; I haven't done this in Windows XP even though it will be pretty much the same method.
I hope my solution helps! And, I welcome comments on my (novice) code from experts in these things - after all, I guess StackOverflow is primarily for that purpose.