I want to created simple Android bluetooth Client-Server program
Server Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
try {
mBluetoothServerSocket=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(name,uUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket=mBluetoothServerSocket.accept();
mInputStream=mBluetoothSocket.getInputStream();
//if(mInputStream.available()>0){
mBufferedReader=new BufferedReader(new InputStreamReader(mInputStream));
data = mBufferedReader.readLine();
tv1.setText(data);
//}
if(mInputStream.available()>0){
data=mBufferedReader.readLine();
tv2.setText(data);
x++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Client Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lb=(Button)findViewById(R.id.button1);
btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdapter.getRemoteDevice(addressHTC);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btAdapter.cancelDiscovery();
btSocket.connect();
String message = "Hello.............. from....... Android......\n";
outStream = btSocket.getOutputStream();
byte[] msgBuffer = message.getBytes();
outStream.write(msgBuffer);
}
catch(IOException e){
e.printStackTrace();
}
lb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String m1="msg 2";
byte[] msgBuffer = m1.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
This application work in one side mode, just Send message to server and show received buffer, But i need to Send back some messages from server to client continuously.
How to do it?
if you have any idea. please share it.
This is works for me for contineously reading. Try it.
try {
BufferedReader Reader = new BufferedReader(
new InputStreamReader(mmSocket.getInputStream()));
while(true)
{
String receivedMsg;
while((receivedMsg = Reader.readLine()) != null)
{
// what you do with your message
}
}
} catch (Exception ex) {
System.out.println(ex);
}
you should have a different thread for listening which will send the message to the activity, this thread can be also the thread sending messages.
that way your the UI wont get stuck and you could receive messages continuously.
an example of such thread:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.util.Log;
public class MessageManager extends Thread {
private static final String TAG = "MessageListener thread";
private BluetoothSocket btConnectedSocket;
private InputStream inStream;
private OutputStream outStream;
private Activity parent;
private boolean run = true;
public MessageManager(BluetoothSocket btConnectedSocket, Activity parent) throws IOException {
this.btConnectedSocket = btConnectedSocket;
this.parent = parent;
inStream = btConnectedSocket.getInputStream();
outStream = btConnectedSocket.getOutputStream();
}
/* this method will listen continuously to messages received through the BT socket until you call cancel
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (run) {
try {
bytes = inStream.read(buffer);
}
catch(IOException ex) {
Log.e(TAG, "error while reading from bt socket");
}
parent.doStuffWithTheMessage(buffer); // pay attention: its in bytes. u need to convert it to a string
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) throws IOException{
outStream.write(bytes);
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
run = false;
try {
btConnectedSocket.close();
} catch (IOException e) { }
}
}
Related
I'm trying to send data from arduino to android app through esp8266. For the moment, arduino and android app are connected via the esp8266 using the TCP/IP socket API. However, when trying to send data continuosly from the arduino it's recieved only once by the android app. In fact, the message is well received by the app only when I proceed the AT+CLOSE command to close the socket and end communication. This method enables me to get the data only one time. So, I have tried to try configure the communication another time after closing it ( please check my code)
void loop()
{
if(Serial1.available())
{
Serial.println("heeeere");
int connectionId = Serial1.read()-48;
while(analogRead(4)>0)
{
convertedvalue = String((analogRead(4)*5)/1024); //convert read analog value before sending it to the android app
convertedvaluelength = String(convertedvalue.length()); //get the length of the converted value
content = "Converted value is "; //make the response to be send to the android app
content += convertedvalue; //make the response to be send to the android app
sendCIPData(connectionId,content);
sendData("AT+CIPCLOSE=0\r\n",1000,DEBUG); //close the connection
delay(10000);
sendData("AT+CIPSERVER=0\r\n",1000,DEBUG); // turn off server
delay(10000);
sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
delay(10000);
}
}
}
Android code :
package com.example.youssefguirat.socketseverywhere;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
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();
socket.sendUrgentData(16);
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 onProgressUpdate(String... values) {
super.onProgressUpdate(values);
textResponse.setText(values[0]);
Toast.makeText(MainActivity.this,"Server:"+values[0], Toast.LENGTH_LONG).show();
Log.w("MSG","Updating with msg");
}*/
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
public class MainActivity extends Activity {
Button buttonSend;
TextView textViewSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textViewSocket = (TextView) findViewById(R.id.textViewSocket);
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Client myClient = new Client("192.168.1.25",80,textViewSocket);
myClient.execute();
}
});
}
}
As you can see, I put a long delay in order to get correct and significant answer from the esp8266 but it didn't work :(busy response when trying to close and configure the server each time I send data
So, can someone help me with it ! I'm really stuck :(
I am working on a chat client application and I have made a server. I managed to make the client connect to the server, but then when I send a message to the server, there's no reaction from the server.
Here is the part of the code of my server that is not working
class ClientConnect implements Runnable {
private DataInputStream in = null;
private DataOutputStream out = null;
Socket client;
ClientConnect(Socket client) {
try {
this.client = client;
/* obtain an input stream to this client ... */
in = new DataInputStream (client.getInputStream());
/* ... and an output stream to the same client */
setOut(new DataOutputStream (client.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
String msg, response;
ChatServerProtocol protocol = new ChatServerProtocol(this);
try {
while (true) {
if (in.available() > 0){
msg = in.readUTF();
response = protocol.process(msg);
getOut().writeBytes("SERVER: " + response);
}
}
} catch (IOException e) {
System.err.println(e);
} finally {
// The connection is closed for one reason or another
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendMsg(String msg) {
try {
getOut().writeBytes(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DataOutputStream getOut() {
return out;
}
public void setOut(DataOutputStream out) {
this.out = out;
}
}
And here is the client :
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String response = null;
EditText nicknameField = (EditText)findViewById(R.id.nicknameField);
EditText passwordField = (EditText)findViewById(R.id.passwordField);
nickname = nicknameField.getText().toString();
password = passwordField.getText().toString();
switch(v.getId()){
case R.id.signin:
new SendMessage(this).execute("SIGNUP " + nickname + " " + password );
break;
case R.id.signup:
new SendMessage(this).execute("SIGNUP " + nickname + " " + password );
break;
}
}
private String onPostExecuteSendMessage() {
return null;
}
public void showMessage(String response) {
Builder builder = new AlertDialog.Builder(this);
builder.setMessage(response);
AlertDialog dialog = builder.create();
dialog.show();
}
public void getClientSocket(Socket client) {
this.client = client;
try {
out = new DataOutputStream (client.getOutputStream());
in = new DataInputStream (client.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DataOutputStream getOut() {
// TODO Auto-generated method stub
return this.out;
}
public DataInputStream getIn() {
// TODO Auto-generated method stub
return this.in;
}
public void goMenuChat() {
// TODO Auto-generated method stub
Intent intent = new Intent(this, MenuChatActivity.class);
startActivity(intent);
}
}
Also I used an Asynctask to send message from the client :
package client.chatclient;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import android.os.AsyncTask;
public class SendMessage extends AsyncTask<String, String, String> {
private static final String msg_OK = "OK";
private static final String msg_NICK_IN_USE = "NICK IN USE";
private static final String msg_UNKNOWN_CMD = "UNKNOWN CMD";
private static final String msg_INVALID = "INVALID COMMAND";
private static final String msg_SEND_FAILED = "FAILED TO SEND";
private static final String msg_INCORRECT_IDS = "INCORRECT IDS";
private static final String msg_DISCONNECT = "DISCONNECT";
private WeakReference<MainActivity> activity;
private String message;
private String response = "";
private DataOutputStream out;
private DataInputStream in;
public SendMessage(MainActivity act){
super();
activity = new WeakReference<MainActivity>(act);
}
protected String doInBackground(String... message) {
this.message = message[0];
this.out = activity.get().getOut();
this.in = activity.get().getIn();
try {
out.writeBytes(this.message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response = convertStreamToString(this.in);
return response;
}
protected void onPostExecute(String response) {
if ((response == msg_INCORRECT_IDS) || (response == msg_NICK_IN_USE)){
activity.get().showMessage(response);
}
else if (response == msg_OK){
activity.get().goMenuChat();
}
}
private static String convertStreamToString(DataInputStream in) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
I send my message from the client by clicking on a button then it goes to the SendMessage class, and send the message to the server and normally the server should receive my message in the loop "while (true)..." and sends back a response according to the protocol that I've implemented.
I really don't know what is wrong. If you know how to solve this issue or have some solutions, please tell me ! If you want more details, ask me ! :)
Thank you very much !
EDIT:
I instanciated my ClientConnect here
public class ChatServer {
private static int port = 8080;
public static void main (String[] args) throws IOException {
ServerSocket server = new ServerSocket(port); /* start listening on the port */
System.out.println( "Listening on "+ server );
Socket client = null;
while(true) {
try {
client = server.accept();
System.out.println( "Connection from " + client );
/* start a new thread to handle this client */
Thread t = new Thread(new ClientConnect(client));
t.start();
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
System.exit(1);
server.close();
}
}
}
}
EDIT: I found where the problem is. I put some log() statements as you said
log.d(null,"beforeconvert")
try {
log.d(null,"convert")
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
log.d(null,"errorconvert")
e.printStackTrace();
}
After that in logcat, it just shows "beforeconvert". I don't really know what the problem is ? while ((line = reader.readLine()) != null) is surely the problem. When I use the debugger step by step in eclipse, it stops at this line and doesn't even go inside the loop.
EDIT : I REALLY don't know why, but when I quit the emulator when running my app, it shows everything.
Listening on ServerSocket[addr=0.0.0.0/0.0.0.0,localport=8080]
Connection from Socket[addr=/127.0.0.1,port=56646,localport=8080]
client connected
msg received
error !
SIGNUP Nickname Password
SIGNUP Nickname Password
msg converted
OK
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at server.ClientConnect.convertStreamToString(ChatServer.java:357)
at server.ClientConnect.run(ChatServer.java:304)
at java.lang.Thread.run(Unknown Source)
java.net.SocketException: Connection reset by peer: socket write error
When you are writing data to output stream in the end you need to flush
this.out.flush();
I think this is why the data is not sent and received
Hope that helps.
Edit:
Let me try to explain in general idea..
When you are opening a socket you have a connection to another machince.
So the
in.available();
and
socket.accpet();
Should work.. once you are writing into outputstream you must flush in order to see the data(or close, i think it flushes before it get closed).
Anyway i attach a link to an example.. You should try this one, Or look at parts you have problem with..
http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/
I am trying to implement code that can recognize different URL requests and perform different actions upon each request, for example, take picture by accessing http://192.168.0.120/pic , and send email by accessing via http://192.168.0.120/email
I already built the code for taking picture and sending email but not sure how to assign them to different URL requests?
I found one code that can run a web server to recognize only one IP address and i want to to modified it to recognize multiple IP addresses and perform different actions upon each request:
The Code:
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class Server extends Thread {
private ServerSocket listener = null;
private static Handler mHandler;
private boolean running = true;
public static LinkedList<Socket> clientList = new LinkedList<Socket>();
public Server(String ip, int port, Handler handler) throws IOException {
super();
mHandler = handler;
InetAddress ipadr = InetAddress.getByName(ip);
listener = new ServerSocket(port,0,ipadr);
}
private static void send(String s) {
Message msg = new Message();
Bundle b = new Bundle();
b.putString("msg", s);
msg.setData(b);
mHandler.sendMessage(msg);
}
#Override
public void run() {
while( running ) {
try {
Socket client = listener.accept();
new ServerHandler(client).start();
LockStatus.getInstance().setMyVar(true);
clientList.add(client);
} catch (IOException e) {
}
}
}
public void stopServer() {
running = false;
LockStatus.getInstance().setMyVar(false);
try {
listener.close();
} catch (IOException e) {
}
}
Thanks a lot
Here is the modification of the code, but still cannot recognize the IP address:
public void run() {
try {
serverSocket = new ServerSocket(SERVERPORT);
while (running) {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String line = null;
String IP = "192.168.0.111";
line = in.readLine();
if (line.equals(IP)) {
new ServerHandler(client).start();
LockStatus.getInstance().setMyVar(true);
Log.i(TAG, "IP Receive=" + line);
// Toast.makeText(getContext(), "Matches",
// Toast.LENGTH_SHORT).show();
} else {
Log.i(TAG, " IP not received :=" + line);
// Toast.makeText(getApplicationContext(), line +" != "+
// IP, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
I've trying to connect 2 devices by sockets, but it never works. One of the devices is the Server that save the configuration (IP and port where listen) on a database, then the other device,the Client , connect with the database and take the configuration to conect.
Database querys and echos works fine (PHP) but the method wich open the client socket doesn't work, it run out of time to connect and throws an exception. I dont know if the ServerSocket doesn't receive the petition or the ClientSocket doesn't send it...
The code below: (bit bad, but is for test).
Server code:
public class Server{
private int puerto = 4567;
private ServerSocket serverSocket;
public void conectar() {
try {
serverSocket = new ServerSocket(puerto);
while (true) {
Log.i("SocketServer", "escuchando");
Socket cliente = serverSocket.accept();
Log.i("Socket","Cliente ha conectado");
BufferedReader ent = new BufferedReader(new InputStreamReader(
cliente.getInputStream()));
String linea = ent.readLine();
Log.i("Cliente", "Cliente envia=" + linea);
cliente.close();
Log.i("Servidor","Cliente desconectado");
}
} catch (IOException e) {
Log.e("Error", "Error en el servidor");
}
}
Client code:
public class Cliente {
private int puerto;
private InetAddress direccion;
public Cliente(int puerto, InetAddress direccion){
this.puerto = puerto;
this.direccion = direccion;
}
public void conectar(){
try{
Socket cliente = new Socket(direccion, puerto);
Log.i("Cliente", "Conectado");
conectado = true;
PrintWriter salida=new PrintWriter(cliente.getOutputStream(),true);
salida.println("Hola, soy el cliente");
Log.i("Cliente", "Mensaje enviado");
cliente.close();
}catch(SocketException e){
Log.e("ErrorSocket","Error al abrir socket " + e.getMessage());
} catch (IOException e) {
Log.e("ErrorSocket","Error al enviar " + e.getMessage());
}
}
}
I get the InetAddress by method below:
//The String result param is like: "192.168.0.1&23456"
public InetAddress getInetAddress(String result) {
InetAddress address = null;
//5 it an example
if (result.length() > 5 && result != null) {
try {
String[] data = result.split("&");
Log.i("Data", data[0] + " " + data[1]);
puerto = Integer.parseInt(data[1]);
Log.i("PUERTO", "Puerto:" + puerto);
String ip = data[0];
Log.i("IP", ip);
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
address = InetAddress.getByAddress(IP);
Log.i("InetAddress",address.getCanonicalHostName());
} catch (Exception e) {
Log.e("Error", "Error al conseguir InnetAddress");
}
} else {
Log.e("Error", "String capturado vacio");
return address;
}
return address;
}
Thanks :)
It a test project for my College Final Project, a GPS-Chat.
EDIT: 3G nat breaks this way to develop an android connection between 2 devices by sockets. I'll study the way to do it with GCM and another server.
For your client code I find that this works really well for me:
OutputStreamWriter wr = new OutputStreamWriter(cliente.getOutputStream());
Then to send data use:
wr.write("DATA TO SEND");
wr.flush();
It looks like you have good logging going on, I would also add Log output lines to see if it got past the socket and have it print out all of the data that you get. If all of the logs show the correct data but the client just won't connect, try the code I posted above, I haven't had problems with it.
ServerApplication.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
public class ServerApp {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable{
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket){
try {
sock=clientSocket;
InputStreamReader isr=new InputStreamReader(sock.getInputStream());
reader=new BufferedReader(isr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
String message;
try {
while((message=reader.readLine())!=null)
{
System.out.println("read :"+message);
tellEveryone(message);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void tellEveryone(String message) {
// TODO Auto-generated method stub
Iterator itr=clientOutputStreams.iterator();
while(itr.hasNext()){
PrintWriter pWriter=(PrintWriter)itr.next();
pWriter.println(message);
pWriter.flush();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ServerApp().createSocket();
}
private void createSocket() {
// TODO Auto-generated method stub
clientOutputStreams=new ArrayList();
try {
ServerSocket socket=new ServerSocket(5000);
while(true){
Socket clientSocket=socket.accept();
PrintWriter writer=new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("Got a Connection to the Client");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Chat Client Source Code
===================================================
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
public class ChatClient {
JTextField outgoing;
JTextArea incoming;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public void layOutDesign(){
JFrame frame= new JFrame("Simple Chat Client");
JPanel mainPanel= new JPanel();
incoming= new JTextArea(15,25);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller=new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing=new JTextField(20);
JButton sendButton=new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setupNetworking();
Thread readerThread=new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(400, 500);
frame.setVisible(true);
}
private void setupNetworking() {
// TODO Auto-generated method stub
try {
sock=new Socket("10.30.10.156", 5000);
InputStreamReader isR=new InputStreamReader(sock.getInputStream());
reader=new BufferedReader(isR);
writer=new PrintWriter(sock.getOutputStream());
System.out.println("Network Established.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class SendButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent ev) {
// TODO Auto-generated method stub
try{
writer.println(outgoing.getText());
writer.flush();
}catch (Exception e1) {
// TODO: handle exception
e1.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ChatClient().layOutDesign();
}
public class IncomingReader implements Runnable{
String message;
#Override
public void run() {
// TODO Auto-generated method stub
try {
while((message=reader.readLine())!=null){
System.out.println("Read :"+message);
incoming.append(message+"\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Go to server code...
and change the IP of your System
then connect to the Clients
And enjoy the Chatting between your colleagues in your Network....
Better option for exchange information about GPS position is use websocket. I very simple server for this kind of application https://github.com/yoman07/geo_server demo class for android you can find here https://github.com/yoman07/PhotoShoter/blob/master/PhotoShoterModule/src/main/java/com/photoshoter/SocketClient.java .
I am writing a simple communication program between Android device 2.2 and Bluetooth RS232 adapter.
I managed to connect and send text successfully, but when reading from the adapter the application crashes.
I do appreciate any help and advice.
Thanks
main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/text_messages"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:text="Button" android:id="#+id/button_listen"
android:layout_width="wrap_content" android:layout_height="wrap_content">
</Button>
</LinearLayout>
MyActivity.java
package com.epostech.bt232test;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
//import android.widget.ArrayAdapter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MyActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 3;
private String mac = "";
private static final UUID MY_UUID_INSECURE = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket clientSocket;
// private ArrayAdapter<String> mArrayAdapter;
private Vector<String> deviceMacs = new Vector<String>();
private Vector<String> deviceNames = new Vector<String>();
#SuppressWarnings("unused")
private Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TextView messageText = (TextView) findViewById(R.id.text_messages);
// messageText.setVisibility(View.VISIBLE);
setContentView(R.layout.main);
Button listenButton = (Button) findViewById(R.id.button_listen);
listenButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// closeSocket();
sendMessage(clientSocket, "P\r\n");
// testing(mac);
}
});
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
String toastText = "";
/*
* if(bluetooth.isEnabled()){ String address= bluetooth.getAddress();
* String name=bluetooth.getName(); toastText=name+" : "+address;
*
* } else
*/
if (!bluetooth.isEnabled()) {
toastText = "Bluetooth is not Enabled!";
Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(this, "BlueTooth Enabled", Toast.LENGTH_LONG).show();
}
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
// Toast.makeText(this,"Size="+pairedDevices.size(),
// Toast.LENGTH_LONG).show();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a
// ListView
deviceMacs.add(device.getAddress());
deviceNames.add(device.getName());
}
} else {
Toast.makeText(this, "Size=" + pairedDevices.size(),
Toast.LENGTH_LONG).show();
}
mac = deviceMacs.get(deviceNames.indexOf("M7705B0125"));
BluetoothDevice device = bluetooth.getRemoteDevice(mac);
try {
clientSocket = device
.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
clientSocket.connect();
// TODO Transfer data using the Bluetooth Socket
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
BluetoothSocketListener bsl = new BluetoothSocketListener(clientSocket, handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendMessage(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = msg.getBytes();
byteString[byteString.length - 1] = 0;
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
// The Handler that gets information back from the BluetoothChatService
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeSocket();
}
}
BluetoothSocketListener.java
package com.epostech.bt232test;
import java.io.IOException;
import java.io.InputStream;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket,
Handler handler, TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
InputStream instream=null;
try {
instream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String message = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = instream.read(buffer);
message = message + new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity
handler.post(new MessagePoster(textView, message));
} catch (IOException e) {
break;
}
}
}
/*
public void run() {
int bufferSize = 256;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead==bufferSize)&&(buffer[bufferSize-1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(textView, message));
//socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
*/
}
MessagePoster.java
package com.epostech.bt232test;
import android.widget.TextView;
public class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
Problem solved
I can read and write to RS232 and display the result on TextView using Handler to communicate with UI and Socket thread.
It was hard excersise but I did it with simple program as follows:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// messageText.setVisibility(View.VISIBLE);
setContentView(R.layout.main);
messageText = (TextView) findViewById(R.id.text_messages);
Button listenButton = (Button) findViewById(R.id.button_listen);
listenButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// closeSocket();
sendData(clientSocket, "P\r\n");
}
});
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
String toastText = "";
/*
* if(bluetooth.isEnabled()){ String address= bluetooth.getAddress();
* String name=bluetooth.getName(); toastText=name+" : "+address;
*
* } else
*/
if (!bluetooth.isEnabled()) {
toastText = "Bluetooth is not Enabled!";
Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(this, "BlueTooth Enabled", Toast.LENGTH_LONG).show();
}
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
// Toast.makeText(this,"Size="+pairedDevices.size(),
// Toast.LENGTH_LONG).show();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a
// ListView
deviceMacs.add(device.getAddress());
deviceNames.add(device.getName());
}
} else {
Toast.makeText(this, "Size=" + pairedDevices.size(),
Toast.LENGTH_LONG).show();
}
mac = deviceMacs.get(deviceNames.indexOf("M7705B0125"));
BluetoothDevice device = bluetooth.getRemoteDevice(mac);
try {
clientSocket = device
.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
clientSocket.connect();
// TODO Transfer data using the Bluetooth Socket
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
BluetoothSocketListener bsl = new BluetoothSocketListener(clientSocket,
handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}// end of onCreate()code
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
messageText.setText(readMessage);
}
};
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// The Handler that gets information back from the BluetoothChatService
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeSocket();
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
private InputStream inStream;
private OutputStream outStream;
public BluetoothSocketListener(BluetoothSocket socket, Handler handler,
TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
try {
outStream = socket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int data;
try {
inStream = socket.getInputStream();
int bytesRead = -1;
String message = "";
// Keep listening to the InputStream while connected
int len= 0;
while (true) {
try {
// Read from the InputStream
bytesRead = inStream.read(buffer);
message= message+new String(buffer,0,bytesRead);
// Send the obtained bytes to the UI Activity
byte[] byteString = message .getBytes();
byteString[byteString.length - 1] = 0;
outStream.write(byteString);
handler.post(new MessagePoster(textView,"Text="+ message+" "+"Bytes read="+bytesRead));
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
private void sendData(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = msg.getBytes();
//byteString[byteString.length - 1] = 0;
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
Dont forget to add the permission to the manifest
<uses-permission
android:name="android.permission.BLUETOOTH" />
I discovered one thing using a serial to BT adapter hooked to a microcontroler.
Often, the data sent to the serial port is a string ended by [].
I used a serial to bluetooth adapter ine one of my projects, sending data lines ended by a and found that handling data with a Scanner rather than a standard buffer really works better.
Example of the Bluetooth Chat modified:
Scanner scan = new Scanner(new InputStreamReader(mmInStream));
String line;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
//Send the obtained bytes to the UI Activity
line = scan.next();
mHandler.obtainMessage(CalibrationS2PActivity.MESSAGE_READ, line.length(), -1, line).sendToTarget();
} catch (Exception e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}