Google glass and sockets - java

I'm trying to connect my Glass with Arduino and a Wifi Shield.
At MenuActivity.java I call (and others methods... but this is the call) :
protected void onCreate(Bundle savedInstanceState)
{
new ConnexioArduino().execute();
super.onCreate(savedInstanceState);
}
And my ConnexioArduino.java :
private boolean socketReady;
private BufferedWriter outA;
private BufferedReader inA;
private Socket mySocket;
....
....
#Override
protected Void doInBackground(Void... params) {
socketReady = true;
String Host = "192.168.43.177";
int Port = 10001;
outA = null;
inA = null;
mySocket = null;
try {
mySocket = new Socket(Host, Port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mySocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
So it only does a connexion between Glass-Arduino Wifi Shield through Socket. But when I execute my app it stops and it gives me the following error : (see image on this link, sorry for the URL I don't have the enough reputation)
http://google-glass-api.googlecode.com/issues/attachment?aid=4630000000&name=Captura+de+pantalla+2014-04-09+a+la%28s%29+13.08.12.png&token=CyuXI9n0-00D4I0inCvN122h42g%3A1398618521508&inline=1

Share your manifest, it should have:
<uses-permission android:name="android.permission.INTERNET"/>
If not you will get a socket failed:eacces (permission denied) error if you step-debug.
Another possible problem is that your server is not accepting the socket request for any number of reasons.
I was able to use your exact code, set up a basic node server on a laptop, and open and close the socket without a crash.
Socket code on Glass should be just like Android according to this:
https://code.google.com/p/google-glass-api/issues/detail?id=272
If you continue to have issues log out the value of e in the exceptions you are catching and paste the result into your question.

Related

Android Studio socket server and client send and recieve data

I'm newer programer in android .. I need help
to sending text between two phone by wifi
first : server
second :client
I'm searching more but i need Simple code and easy to help me
thnx for advance
I guess sockets is what you are looking for...
To create a socket in android the socket must be created in a thread.
Client side example:
private final String IP = "9.9.9.9";
private final int PORT = 8080;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new MainThread()).start();
}
class MainThread implements Runnable {
#Override
public void run() {
try {
InetAddress address = InetAddress.getByName(IP);
socket = new Socket(address,PORT);
new Thread(new GetThread()).start();
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class GetThread implements Runnable {
#Override
public void run() {
try {
InputStreamReader isR=new InputStreamReader(socket.getInputStream());
BufferedReader bfr=new BufferedReader(isR);
while(true) {
String textMessage = bfr.readLine();
// TODO: Insert logic which use the recived message (textMessage)
}
}
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
In the thread, the socket is waiting for data to be sent (while(true)).
and the IP is the ip of the server (if you are connecting to your computer
with wifi, you should check your ip address with ipconfig in the command line).

android client side doesnt read after a while

It's my first question in here. I hope i can find answer. Subject is that, i have server (arduino). it send and receive data.it send data when take a data from client side(android). Android side is send data when push button. Also android has use Speech to Text (google API).So when we push button or use speechrecognation, client side send a data.But it reads socket continuously. I have two kind android device. One device work well about data receiving but it is not good about speechrecognation. One device very well about voice but after a while socket is happened useless. We must push reset button on arduino and reset android app. (My first android device version is 5.1.1 second is 6.0). Sorry for my english. I hope i can tell my problem :)
.
.
.
public void senddata(String asd){
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(asd);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
.
.
.
class ClientThread implements Runnable {
#Override
public void run() {
BufferedReader inStream = null;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
//socket.setSoTimeout(1000);
// Get the input and output streams
inStream = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
// Confirm that the socket opened
// Read messages in a loop until disconnected
while( true){
String msg= inStream.readLine();
Log.e("GELENLER::::",msg);
gelenkomut=msg;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
gelenparse(gelenkomut);
}
});
// Send it to the UI thread
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
finally {
try {
inStream.reset();
inStream.
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

tcp connection between Android server and PC client

Server part(Android)
new Thread(new Runnable() {
public void run() {
DatagramSocket s;
try {
s = new DatagramSocket();
s.send(new DatagramPacket("aaa".getBytes(), 3, InetAddress.getByName(/* Server ip address*/), 11720));
s.close();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true)
{
try {
ServerSocket ssocket = new ServerSocket(11720);
ssocket.accept(); // Cannot make connection!!
Toast.makeText(a, "Who's coming", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
Client code (Java, PC)
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(11720);
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
ds.close();
try {
ds.receive(dp);
// ds.send(new DatagramPacket("aaaa".getBytes(), 4, dp.getAddress(), 11720));
Socket socket = new Socket(dp.getAddress(), 11720); // Cannot make connection!!
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to make connection between android server and pc client.
First android send a packet to pc.
I think server can know using this packet, so I use function getAddress().
Then android open socket using port number 11720 and pc try to connect android.
But it cannot connect.
Why this code cannot make connection?
Oh, I just want to know how can I connect from pc to phone.
So I change pc and android code.
Firstly, my goal is connect to android using static port(11720).
But I cannot make connection using static port when using LTE.
So I check socket information using simple program.
This is in pc.
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(11720);
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
while (true)
{
ds.receive(dp);
System.out.println(dp.getSocketAddress());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is in android.
new Thread(new Runnable() {
public void run() {
try {
DatagramSocket s = new DatagramSocket(11720);
while(true)
{
s.send(new DatagramPacket("aaa".getBytes(), 3, InetAddress.getByName("143.248.55.131" /* Server address */), 11720));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
I execute programs using WiFi and LTE.
And result is
/143.248.56.118:11720 <- using WiFi
/143.248.56.118:11720
/143.248.56.118:11720
/117.111.7.124:35645 <- change LTE
/117.111.7.124:35645
/117.111.7.124:35645
When using LTE, socket's port number is changed.
so I cannot send packet using static port number.
How can I solve this problem?
Firstly, why are you complicating by using Datagram Socket unnecessarily?
You can simply use TCP without any problems.
Well, your client code(Java PC) might be waiting at:
ds.receive(dp);
And so the socket might not get created.
Although the android program is sending a packet but UDP being unreliable, the packet may not be received by the client code.
Also, this can be due to network issues like both cannot get a connection, or there might be a NAT between them which would not let any UDP packet to let in.
So, I would suggest to simply use TCP. Don't complicate by first sending a UDP packet and then connecting with TCP.

Cant read data from TCP Server with Android Client APP

That is my program in java for my android app. I tried to create tcp connection with tcp server. I can connect to server with another applications so that i can send and receive from tcp server. With my code and with my program i can send messages to server very eazy, but i have troubles with receiving messages from server.
private Socket socket;
private final int SERVERPORT = 6060;
private final String SERVER_IP = "192.168.0.8";
public TextView tv;
private PrintWriter out;
private InputStream in;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)this.findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
}
Here is my problem i dont know how to receive strings or bytes from server. When i run my app on phone it closes the open window and say that program stop working. If i delete this section of code(public void ONCLICK2) i can transmit messages to server.
public void ONCLICK2(View view) {
try {
in=socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte array[]=new byte[1];
try {
int i=in.read(array);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So please help me with that section of code. How can i receive string send from TCP server.
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
out.println(str);
out.flush();
}catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Simply put, the problem is you are intercepting the byte array of an unknown length and attempting to store them in array the size of one. Furthermore, it is ideal to append the packet size prior to the data in the packet and perhaps create the intercept in a separate thread waiting for incoming packets.
To just fix your ONCLICK2 you should do the following:
byte[] data = new byte[6556];
try {
in = socket.getInputStream();
// NOTE: The data byte array will contain empty values if
// under the size of 6556
int size = in.read(data);
// send to LogCat
Log.e("String", data.toString());
} catch (Exception e) {
e.printStackTrace();
}
I have not tested this code, but this should fix your problem.

Data from Android Mobile to Java Application through Socket

I want to transfer data from Android device to the java desktop server. I have a text and button. As I press the button on the device, the text should be displayed on the java desktop server. I also have added AsyncTask in the client. The error code has also been added. The port i have used is 4444 and the ip address I used is of my local host address.
I am doing a very silly mistake. Can you please guide me.
I run the server code, it first gives me : Server started. Listening to the port 4444.
Now, I run the client code and write something on my mobile. As I press my button, it gives me error. And the app crashes and closes. I am a new one. Thanks in advance.
Client Code :
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1); //reference to the text field
button = (Button) findViewById(R.id.button1); //reference to the send button
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
messsage = textField.getText().toString(); //get the text message on the text field
textField.setText(""); //Reset the text field to blank
try {
client = new Socket("134.190.162.165", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public class Asynctask extends AsyncTask<View, Integer, Socket>
{
private static final String IP_ADDRESS = "134.190.162.165"; // Toshiba laptop
// private static final String IP_ADDRESS = "10.0.0.2"; // Toshiba laptop
private static final int DEST_PORT = 4444;
private EditText mTextField;
/**
* Store provided views (used later in onPostExecute(...)).
*
* Create socket to communicate with server (blocking call).
*/
protected Socket doInBackground(View... params)
{
// Store provided views.
if (params.length != 1)
throw new IllegalArgumentException();
mTextField = (EditText) params[0];
// Create socket.
Socket client = null;
try
{
client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return client;
}
/**
* Write to server.
*/
protected void onPostExecute(Socket client)
{
try
{
PrintWriter printwriter;
String messsage;
messsage = mTextField.getText().toString(); // get the text message on the text field
mTextField.setText(""); // Reset the text field to blank
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Server Code:
public class server {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); //Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); //accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
The error which I get is:
FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
libcore.io.IoBridge.connectErrno(IoBridge.java:127)
libcore.io.IoBridge.connect(IoBridge.java:112)
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
java.net.Socket.startupSocket(Socket.java:572)
java.net.Socket.tryAllAddresses(Socket.java:127)
java.net.Socket.<init>(Socket.java:177)
java.net.Socket.<init>(Socket.java:149)
com.example.client.MainActivity$1.onClick(MainActivity.java:42)
android.view.View.performClick(View.java:3567)
In the manifest file, I have added all the requirements. It does not give any compile time error.
I checked from many websites but the code which is working is this only. But I dont know where I am making mistake in running it or somewhere else.
If any other option is there, please suggest me, i am scratching my head since long
Thanks
Your code seems very confusing. The client seems to have code for doing the network connection and I/O both on the main thread (in the OnClickListener attached to button) and in the AsyncTask (which is never created). Try this for an OnClickListener:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
message = textField.getText().toString(); //get the text message on the text field
textField.setText(""); //Reset the text field to blank
new Asynctask().execute(message);
}
});
But you have another problem: while your AsyncTask is (correctly) making the socket connection in doInBackground, it is incorrectly doing the network I/O in onPostExecute. The network I/O also needs to be done in the background. Try this for an AsyncTask:
public class Asynctask extends AsyncTask<String, Void, Void> {
private static final String IP_ADDRESS = "134.190.162.165"; // Toshiba laptop
// private static final String IP_ADDRESS = "10.0.0.2"; // Toshiba laptop
private static final int DEST_PORT = 4444;
private EditText mTextField;
/**
* Store provided views (used later in onPostExecute(...)).
*
* Create socket to communicate with server (blocking call).
*/
protected Void doInBackground(String... messages) {
if (messages.length != 1) { return null; }
String message = messages[0];
// Create socket.
Socket client = null;
try {
client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Write to server.
try {
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The above is entirely untested, so it may not be exactly right. I also didn't look at your server code; this answer just addresses the NetworkOnMainThreadException problem.

Categories

Resources