Android : How to Send a string over wi-fi without using printwriter? - android

The program here shows passing a string using wi-fi. I need a solution which does not require print writer or a simple solution which helps me send two different strings while toggling the buttons
switch3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (switch3.isChecked()) {
messsage = "S";
Log.d("On", "Button On" + messsage);
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
// client = new
// Socket(etIP.getText().toString(), port);
client = new Socket("192.168.4.1", 100);
printwriter = new PrintWriter(client
.getOutputStream(), true);
printwriter.write(messsage);
printwriter.flush();
//printwriter.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} else {
messsage = "T";
Log.d("off", "Button off " + messsage);// etMsg.getText().toString();
// etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
// client = new
// Socket(etIP.getText().toString(), port);
//client = new Socket("192.168.4.1", 100);
printwriter = new PrintWriter(client
.getOutputStream(), true);
printwriter.write(messsage);
printwriter.flush();
//printwriter.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}
});

You can send data by this way ->
try {
Socket socket = new Socket(DESTINATION_ADDRESS, DESTINATION_PORT);
// Exmp : Socket socket = new Socket("192.168.0.101", 80);
OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(SEND_STRING);
// Exmp : out.writeUTF("TEST");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}

Related

Android get data from pc using socket

Android send data to pc - client side (work with success):
Button send = (Button) findViewById(R.id.sendSocket);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Socket socket = new Socket("IP",8000);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("Hello");
socket.close();
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Now How can i keep listening to receive data from pc (server side) ???
that's what i am tryng (not working) :
try {
Boolean end = false;
ServerSocket ss = new ServerSocket(8000);
while(!end){
//Server is waiting for client here, if needed
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
recive.setText(st);
s.close();
//if ( STOPPING conditions){ end = true; }
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
recive.setText(e.toString());
}
try something like this :
ServerSocket ss = new ServerSocket(8000);
Socket s = ss.accept();
BufferedReader input = new BufferedReader (new InputStreamReader (s.getInputStream ()));
while (true)
{
String st = "";
try
{
st = input.readLine ();
System.out.println (st);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}
ss.close();

data not sent using bluetooth socket (android)

I am trying to send a file using Android bluetooth sockets. I am getting the pairing requests but unfortunately the data is not being transferred
my Server side and client side is as follows:
Server: (for my application server is receiving the data)
public void run() {
super.run();
BluetoothAdapter mBtadapter = BluetoothAdapter.getDefaultAdapter();
Log.i("bluetooth Adapter", "got adapter "+ mBtadapter.getAddress());
try {
Ssocket = mBtadapter.listenUsingRfcommWithServiceRecord("CardXchange", uuid);
Log.i("Socket", "Socket Acquired "+ Ssocket.toString());
} catch (IOException e) {
e.printStackTrace();
}
while(true){
if(read_flag()==1){
try {
Toast.makeText(c, "flag is eventually 1", Toast.LENGTH_LONG).show();
Ssocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
try {
client_socket = Ssocket.accept();
if(client_socket!=null){
//this function is used to handle the connection when sockets get connected
manageConnection1(client_socket);
Ssocket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("breaked ", "oh god!! out of the loop ");
}
//implementation of the function
private void manageConnection1(BluetoothSocket client_socket2) {
// TODO Auto-generated method stub
int bytes;
Log.i("serevr chya manage connection madhe gela", "in servers manage connection ");
File file = new File("/sdcard/myfolder/received.Xcard");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
InputStream is = client_socket2.getInputStream();
while((bytes = is.read(buffer, 0, 1024))>0){
fos.write(buffer, 0, 1024);
}
is.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
client_socket2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and the client side (the sending side is like this):
public void run(){
try {
Method m = send_dev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
Csocket = (BluetoothSocket) m.invoke(send_dev, 1);
Csocket.connect();
manageSendConnection(Csocket);
}catch(Exception e){
e.printStackTrace();
}
}
//function to handle after connection is established.
private void manageSendConnection(BluetoothSocket csocket) {
// TODO Auto-generated method stub
File f = new File("/sdcard/myfolder/card3.Xcard");
byte[] buffer = new byte[(int)f.length()];
try {
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(buffer, 0, (int)f.length());
OutputStream os = csocket.getOutputStream();
os.write(buffer);
os.close();
fis.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
csocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am getting the pairing request but the data is not being sent.
can anyone please help me to find the problem and give a hint on solution??

Android: Socket is closed

PCClient :
public class PCServer
{
/**
* #param args
*/
static Socket socket = null;
private static String ip = "192.168.42.129";
private static int port = 18181;
public static void main(String[] args)
{
// TODO Auto-generated method stub
try
{
socket = new Socket(ip, port);
} catch (UnknownHostException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
SendMsg(ip, port, "BZT");
GetMessage getMessage = new GetMessage();
getMessage.start();
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void SendMsg(String ip, int port, String msg) throws UnknownHostException, IOException
{
try
{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write(msg);
writer.flush();
writer.close();
//socket.close();
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
static class GetMessage extends Thread
{
#Override
public void run()
{
// TODO Auto-generated method stub
super.run();
try
{
while (true)
{
System.out.println("--------------------------------------------------------");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
System.out.println(str);
//client.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
AndroidServer : Service
public class SocketService extends Service
{
public static final int SERVERPORT = 18181;
ServerSocket serverSocket;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO Auto-generated method stub
try
{
serverSocket = new ServerSocket(SERVERPORT);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
GetSocketMessage getSocketMessage = new GetSocketMessage();
getSocketMessage.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
try
{
this.serverSocket.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class GetSocketMessage extends Thread
{
#Override
public void run()
{
// TODO Auto-generated method stub
super.run();
try
{
Log.i("s", "S: Connecting...");
while (true)
{
Socket client = serverSocket.accept();
Log.i("s", "S: Receiving...");
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
Log.i("s", "S: Received: '" + str + "'");
if ("BZT".equals(str))
{
Intent intent = new Intent("com.StarHope.ZWGKXT.connected");
sendBroadcast(intent);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("OK");
writer.flush();
writer.close();
}
if ( Lbjy_usbActivity.content !=null )
{
Log.i("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "oooooooooooooooooooooooooooooo");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
writer.write("");
writer.flush();
writer.close();
}
}
catch (Exception e)
{
Log.i("s", "S: Error");
e.printStackTrace();
}
finally
{
Log.i("s", "S: Done");
}
}
}
catch (Exception e)
{
Log.i("s", "S: Error");
e.printStackTrace();
}
}
}
}
The android phone server can received the message sent from PCClient "BZT",
But when the phone send "OK" to PC , there is always an
Exception:java.net.SocketException: Socket is closed.
How can I fix this?
Closing any stream obtained using getOutputStream() or getInputStream() closes the socket.
Do you receive something before 'BZT' ? If so, the socket will be closed after you sent the empty answer.
You should use only one output stream, and flush() each message without closing.

Android Socket communication Exception

My server code
public class RemoteServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF().toUpperCase());
dataOutputStream.writeUTF("sajol");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
My client code for android device
public class Client extends Activity {
EditText textOut;
TextView textIn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Button b = findViewById(R.id.b)
textOut = (EditText) findViewById(R.id.t);
Button buttonSend = (Button) findViewById(R.id.b);
textIn = (TextView) findViewById(R.id.te);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread t = new Thread(r);
t.start();
}
};
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.239", 8888);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("Sajol", e+"");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Sajol", e+"");
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Sajol", e+"");
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Sajol", e+"");
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Sajol", e+"");
}
}
}
}
};
}
when i run this client code on emulator server response .But when i run client code on real device server program does not response.I found the ip address using in my code by execute ipconfig command on cmd. My pc(windows 7) and android device both are connected to wifi.
i got following exception
java.net.SocketTimeoutException: Connection timed out
Please give me solution

android socket application, sockets send only the first time

I have an android client that listens to the smartphone's sensors and when it detects a variation in a sensor's value it produces a string (a "command"), and creates a socket and an output stream to send the string to a java server; every sensor listener creates a socket with a different port than the other listeners. I have also a "send" button and a textbox to send any other string to the server. The problem is that while the button "send" works fine and sends all the strings written in the textbox every time i press it, every listener sends the "command" only the first time they detect a variation in the sensors' values..
//listener buttonSend
Button.OnClickListener buttonSendOnClickListener = new Button.OnClickListener()
{
#Override
public void onClick(View arg0)
{
buttonSend.setEnabled(false);
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try
{
socket = new Socket(IP, 32450);
socket.setReuseAddress(true);
socket.setSoTimeout(2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
}
catch (UnknownHostException e)
{
e.printStackTrace();
buttonSend.setEnabled(true);
}
catch (IOException e)
{
e.printStackTrace();
buttonSend.setEnabled(true);
}
finally
{
if (socket != null)
{
try
{
buttonSend.setEnabled(true);
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
buttonSend.setEnabled(true);
}
}
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (dataInputStream != null)
{
try
{
dataInputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}; //End listener buttonSend
this was the button and all the sensors work like this:
//proximity sensor event listener
SensorEventListener proximitySensorEventListener
= new SensorEventListener()
{
public void onAccuracyChanged(Sensor arg0, int arg1)
{
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent arg0)
{
// TODO Auto-generated method stub
if(arg0.sensor.getType()==Sensor.TYPE_PROXIMITY && IP!="")
{
textProximitySensorData.setText("Proximity Sensor Value:"
+ String.valueOf(arg0.values[0]));
String proxValue = "Proximity Sensor: VALUE "
+ String.valueOf(arg0.values[0]);
if(buttonSend.isEnabled()==true){
Socket socket = null;
DataOutputStream dataOutputStream = null;
try
{
socket = new Socket(IP, 32452);
socket.setReuseAddress(true);
socket.setSoTimeout(2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(proxValue);
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (socket != null)
{
try
{
socket.close();
socket=null;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null)
{
try
{
dataOutputStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
};
i tried setSoTimeout but it's useless because it's only for read, and setReuseAddress but it didn't work, logcat and console don't show any error when i run the application, can you help me finding the problem?

Categories

Resources