Socket serveur qui envoie un message retour au client.
Bonjour à tous et à toutes ! :zoubi:
J’espère que vous allez bien ;) ?
Je réalise un petit projet et j'essaye d'afficher une image sur une application Android lorsque je clique sur un capteur relié à une Raspberry (codé en python). Il y a 4 capteurs donc 4 images différentes à afficher sur l'application. Donc lorsque l'application reçois une data de la Raspberry il affiche une image en conséquence.
Je suis débutante en java et en application Android.
J'ai voulue réaliser l'opération décrite précédemment en appliquant un protocole TCP via des sockets.
Ma Raspberry en tant que serveur et mon téléphone Android en tant que Client.
Pour le moment je me concentre sur la partie communication, j'ai suivi un tuto (sans faire la magicienne, c'est à dire comprendre le code et non juste l’exécuter).
-J'arrive à établir une connexion entre mon téléphoné et la Raspberry, à envoyer un message du téléphone à la Raspberry mais je n'arrive pas à afficher le message retour sur le téléphone. En fait je ne sais pas comment afficher ce message dans un TextView...
Exit-il une méthode plus facile que passer par un application mobile, peut-on envoyer un message retour du serveur au client ?
Merci et bonne journée ! :P
Voici mon code côté serveur (Raspberry):
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import socket
import time
listensocket = socket.socket()
Port = 10
maxConnections = 999
IP = socket.gethostname() #Hostname de la machine
listensocket.bind(('',Port))
#Ouverture de serveur
listensocket.listen(maxConnections)
print("Server sur " + IP + " sur port " + str(Port))
#Accept connection
(clientsocket, address) = listensocket.accept()
print("Conncection faite!")
running = True
#Main
while running:
message = clientsocket.recv(1024).decode() #Recevoir Message
print(message)
output = 'Serveur répond au client'
clientsocket.sendall(output.encode('utf-8'))
clientsocket.close()
running = False |
Voici le code côté Android studio :
MainActivity :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| package com.limeparallelogram.socketclient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
public String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText inputtext = (EditText)findViewById(R.id.editText3);
final Button clickable = (Button)findViewById(R.id.button3);
clickable.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
send sendcode = new send();
message = inputtext.getText().toString();
sendcode.execute();
}
});
}
class send extends AsyncTask<Void,Void,Void> {
Socket s;
PrintWriter pw;
@Override
protected Void doInBackground(Void...params){
try {
s = new Socket("192.168.43.64",10);
pw = new PrintWriter(s.getOutputStream());
pw.write(message);
//Message retour
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String retour = br.readLine();
System.out.println("Message received from the server : " +retour);
pw.flush();
pw.close();
s.close();
} catch (UnknownHostException e) {
System.out.println("Fail");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Fail");
e.printStackTrace();
}
return null;
}
}
} |
Manifest :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.limeparallelogram.socketclient" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest> |
activity_main:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.limeparallelogram.my_application.MainActivity">
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/message"
android:inputType="textPersonName"
android:text="@string/message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText3"
app:layout_constraintVertical_bias="0.113" />
</android.support.constraint.ConstraintLayout> |