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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
| package com.example.nadia.helloword;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
// pour socket besoin d'importer le bibilothéque
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
// Tag for logging
private final String TAG = getClass().getSimpleName();
// AsyncTask object that manages the connection in a separate thread
WiFiSocketTask wifiTask = null;
// nos boutton
EditText textStatus, editTextAddress, editTextPort;
Button buttonConnect, buttonDisconnect
buttonON,buttonOFF;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// référence pour les élements
textStatus = (TextView) findViewById(R.id.textStatus);
editTextAddress = (EditText) findViewById(R.id.address);
editTextPort = (EditText) findViewById(R.id.port);
buttonON = (Button) findViewById(R.id.ON);
buttonOFF = (Button) findViewById(R.id.OFF);
buttonConnect = (Button) findViewById(R.id.connect);
/** tentative de connection */
public void connectButtonPressed(View v) {
if (wifiTask != null) {
setStatus("Already connected!");
return;}
try {
// Get the remote host from the UI and start the thread
String host = editTextAddress.getText().toString();
int port = Integer.parseInt(editTextPort.getText().toString());
// Start the asyncronous task thread
setStatus("Attempting to connect...");
wifiTask = new WiFiSocketTask(host, port);
wifiTask.execute();
}
catch (Exception e) {
e.printStackTrace();
setStatus("Invalid address/port!");}
}
/**disconnecter*/
public void disconnectButtonPressed(View v) {
if (wifiTask == null) {
setStatus("Already disconnected!");
return;}
wifiTask.disconnect();
setStatus("Disconnecting..."); }
/**
* Invoked by the AsyncTask when the connection is successfully established.
*/
private void connected() {
setStatus("Connected.");
// buttonSend.setEnabled(true);
}
/**
* Invoked by the AsyncTask when the connection ends..
*/
private void disconnected() {
setStatus("Disconnected.");
//buttonSend.setEnabled(false);
wifiTask = null;
}
private void turnOffLed()
{
if ( wifiTask!=null)
{
try
{
wifiTask.getOutputStream().write("TF".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if ( wifiTask!=null)
{
try
{
wifiTask.getOutputStream().write("TO".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
public class WiFiSocketTask extends AsyncTask<Void, String, Void> {
String address;
int port;
// Special messages denoting connection status
private static final String PING_MSG = "SOCKET_PING";
private static final String CONNECTED_MSG = "SOCKET_CONNECTED";
private static final String DISCONNECTED_MSG = "SOCKET_DISCONNECTED";
Socket socket = null;
BufferedReader inStream = null;
OutputStream outStream = null;
// Signal to disconnect from the socket
private boolean disconnectSignal = false;
// Socket timeout - close if no messages received (ms)
private int timeout = 5000;
// constructeur
WiFiSocketTask(String address, int port) {
this.address = address;
this.port = port;
}
/**
* Main method of AsyncTask, opens a socket and continuously reads from it
*/
@Override
protected Void doInBackground(Void... arg) {
try {
// ouvrir une socket et se connecter
socket = new Socket();
socket.connect(new InetSocketAddress(address, port), timeout);
// Get the input and output streams
inStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outStream = socket.getOutputStream();
// confirmation de la connexion de socket
if(socket.isConnected()) {
// tester si l'input stream est prete
long start = System.currentTimeMillis();
while(!inStream.ready()) {
long now = System.currentTimeMillis();
if(now - start > timeout) {
Log.e(TAG, "Input stream timeout, disconnecting!");
disconnectSignal = true;
break;
}
}
} else {
Log.e(TAG, "Socket did not connect!");
disconnectSignal = true;
}
// Read messages in a loop until disconnected
while(!disconnectSignal) {
// Parse a message with a newline character
String msg = inStream.readLine();
// Send it to the UI thread
publishProgress(msg);
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Error in socket thread!");
}
publishProgress(DISCONNECTED_MSG);
// fermture de la socket, instrem et outstrem
try {
if (socket != null) socket.close();
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
} |
Partager