android socket connection failed? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Im' writing a sample chat program that sends message between 2 android phones, so I wrote the following and let a phone connect to itself(10.0.2.2 or localhost) to test it the code works or not.
But looks like in the thread of receivemsg(), the socket is never connected. So did I use the wrong ip address to refer to myself? or does my code have something wrong? thank you for your help!
package com.example.chatroomprogram;
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.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class ClientActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
public String ipaddress;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
Intent intent = getIntent();
ipaddress=intent.getStringExtra("ipaddress");
Log.i("123","ip is "+ipaddress);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
//msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
// receiveMsg();
//----------------------------
//server msg receieve
//-----------------------
//End Receive msg from server//
}
public void sendMessageToServer(String str) {
final String str1=str;
new Thread(new Runnable() {
#Override
public void run() {
//String host = "opuntia.cs.utep.edu";
//String host="10.0.";
String host2 = "10.0.2.2";
PrintWriter out = null;
Socket socket = null;
try {
socket = new Socket("10.0.2.2", 8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("123","not null");
// out.println("hello");
out.println(str1);
Log.i("123", "hello");
out.flush();
}
}).start();
}
public void receiveMsg()
{
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
//final String host="opuntia.cs.utep.edu";
final String host="10.0.2.2";
//final String host="127.0.0.1";
Socket socket = null ;
BufferedReader in = null;
try {
//socket = new Socket(host,8008);
ServerSocket ss = new ServerSocket(8008);
socket = ss.accept();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true)
{
String msg = null;
try {
msg = in.readLine();
Log.i("123","MSGGG: "+ msg);
//msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(msg == null)
{
break;
}
else
{
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg)
{
final String mssg=msg;
handler.post(new Runnable() {
#SuppressLint("NewApi")
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.i("123","hi");
}
});
}
}
update: Problem solved, conclusion: if you use AVD, just use 10.0.2.2; if you use an actual phone to debug, you can use localhost

my bad... i used 10.0.2.2 and it works...

Related

Android. Sockets. Fail Connection

I develop simple client-server app for Android by examples:
http://android-er.blogspot.com/2014/02/android-sercerclient-example-server.html
http://android-er.blogspot.com/2014/02/android-sercerclient-example-client.html
Server code:
package com.example.androidserversocket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
infoip.setText(getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Android, you are #" + cnt;
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replayed: " + msgReply + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
Client code:
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView)findViewById(R.id.response);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonClear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
textResponse.setText("");
}});
}
OnClickListener buttonConnectOnClickListener =
new OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#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();
/*
* notice:
* inputStream.read() will block if no data return
*/
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 onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
I work with TWO emulators Android.
When server starts it gets IP: 10.0.2.15
And in Client window I set IP: 10.0.2.15 and PORT:8080.
But I get exception: "Failed to connect to /10.0.2.15 (port 8080): connect failed: ECONNREFUSED (Connection refused)"
Why I can not connect?
Just to recap this as an answer: Testing on a real device should solve the issue. Apps generally have to be tested on at least one (better several) real device. Especially trying to connect an emulator to another emulator on the same PC is not even remotely close to a real situation. One device would be enough for you. That is, a real Android can connect to an emulator or the other way round as long as the PC allows the connection.

Android USB to Serial Receive Error

I'm currently working on writing an App on Android to interface with an Arduino Board. I am able to send serial data to my Arduino just fine, however my app crashes at start up the moment I begin trying to receive data.
I currently have it set so a text field takes data from a user, and sends to the Arduino, Arduino does a function.
For my receive, I am making a new thread at start up to constantly listen for data from the Arduino. whenever the code in this thread is executed, it crashes.
I am using this library as my basis: https://github.com/mik3y/usb-serial-for-android
Below is the all the code pertinent, omitted code for other functionality this app is providing, that are unrealted:
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import android.hardware.usb.UsbManager;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.content.Context;
import android.util.Log;
import com.hoho.android.usbserial.driver.UsbSerialProber;
public class MainActivity extends Activity implements SensorEventListener, LocationListener{
private EditText sendTextField;
TextView uartRX;
public Handler Handler;
UsbManager manager;
/** Called to create application activity*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uartRX = (TextView)findViewById(R.id.rxUART);
sendTextField = (EditText) findViewById(R.id.sendTextField);
Handler = new Handler() {
#Override public void handleMessage(Message msg) {
String text = (String)msg.obj;
uartRX.append(text);
}
};
Thread t = new Thread(new Runnable() {
public void run()
{
Message msg = new Message();
msg.obj = "Start Serial Listen\n";
Handler.sendMessage(msg);
rxUART();
}
public void rxUART()
{
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbSerialDriver rxDriver = UsbSerialProber.acquire(manager);
if (rxDriver != null) {
try {
rxDriver.open();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
int byteSize = 0;
String data = "";
while(true)
{
byte[] arr = null;
try {
rxDriver.setBaudRate(115200);
rxDriver.read(arr, byteSize);
data = new String(arr);
Message msg = new Message();
msg.obj = data;
Handler.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t.start();
}
public void sendUART(String data)
{
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
// Find the first available driver.
UsbSerialDriver driver = UsbSerialProber.acquire(manager);
if (driver != null) {
try {
driver.open();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
driver.setBaudRate(115200);
byte buffer[] = new byte[16];
int numBytesRead = driver.read(buffer, 1000);
Log.d(TAG, "Read " + numBytesRead + " bytes.");
byte temp[] = data.getBytes();
driver.write(temp, 16);
} catch (IOException e) {
// Deal with error.
} finally {
try {
driver.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public void onClickSendBtn(View v)
{
String data = "";
data = sendTextField.getText().toString();
sendUART(data);
sendTextField.setText(" ");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Can anyone help me figure out why the app crashes on the code created in the thread?
Note: the code also crashes when not in a thread. Code was originally a function called by sendUART() to check for a response. no while(true) either.
Logcat:
11-02 09:49:22.988: E/AndroidRuntime(22652): FATAL EXCEPTION: Thread-964
11-02 09:49:22.988: E/AndroidRuntime(22652): java.lang.NullPointerException
11-02 09:49:22.988: E/AndroidRuntime(22652): at com.example.sensortest.MainActivity$2.rxUART(MainActivity.java:143)
11-02 09:49:22.988: E/AndroidRuntime(22652): at com.example.sensortest.MainActivity$2.run(MainActivity.java:119)
11-02 09:49:22.988: E/AndroidRuntime(22652): at java.lang.Thread.run(Thread.java:856)
The line numbers referenced are:
Thread t = new Thread(new Runnable() {
public void run()
{
Message msg = new Message();
msg.obj = "Start Serial Listen\n";
Handler.sendMessage(msg);
rxUART();
}
public void rxUART()
{
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbSerialDriver rxDriver = UsbSerialProber.acquire(manager);
if (rxDriver != null) {
try {
rxDriver.open();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
int byteSize = 0;
String data = "";
while(true)
{
byte[] arr = null;
try {
rxDriver.setBaudRate(115200);
rxDriver.read(arr, byteSize);
data = new String(arr);
Message msg = new Message();
msg.obj = data;
Handler.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t.start();
You don't handle the case rxDriver == null in rxUart() correctly.
The if() statement skips the open() call only, but the while() loop gets executed with rxDriver being NULL resulting in NPE. You have the same problem in `sendUART(), btw.

Two different string pass from android to pc by single toggle button using wifi

In my android project, i have successfully passed 2 strings[(TV ON(by button 1) and TV OFF(by button 2)] from my android phone to my PC by 2 simple button using WiFi.but here i need to pass 2 strings using single toggle button [(TV ON(click on toggle button) and TV OFF(again click on toggle button)] instead of 2 simple button(which is mentioned above).
sorry for my bad English.
thanks in adv.
java code-
package com.example.wifitoggle;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.widget.ToggleButton;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private Button button;
private Button button1;
private ToggleButton toggleButton1;
private String messsage;
int port = 0; //
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// etIP = (EditText) findViewById(R.id.editText1);
// etPort = (EditText) findViewById(R.id.editText2);
//etMsg = (EditText) findViewById(R.id.editText3);
button = (Button) findViewById(R.id.button1);
button1 = (Button) findViewById(R.id.button2);
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
messsage = "TV ON" ; //etMsg.getText().toString();
//etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4",2000);
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();
}
});
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
messsage = "TV OFF" ; //etMsg.getText().toString();
//etMsg.setText("");
// port = Integer.parseInt(etPort.getText().toString());
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4",2000);
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();
}
});
}
}
Try this..
toggleButton1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//do something if on
}else{
//do something if off
}
});
An alternative to this
toggleButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((toggleButton1.isChecked()))
{
//do something if on
}
else
{
//do something if off
}
}
});
here is the correct code
mToggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mToggleButton.isChecked()) {
messsage = "TV ON";
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("1.2.3.4", 2000);
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 = "TV OFF";
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("1.2.3.4", 2000);
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();
}
}
});
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
// client = new Socket(etIP.getText().toString(), port);
client = new Socket("1.2.3.4", 2000);
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();

Java sockets server help

Hi there im very new to java programing and am really stuck getting a socket server and client working how i want.
The problem im having is...
server:
Im looking at the output from the client and once client prints "TIME" the server will return a message eg "the time is...". The server does this but not straight away it seems to send it on the second time you send a message from the client.
Is this becuase the client is not connected all the time maybe ?
Im pretty sure this method is wrong can anyone give me some advice.
Any help would be great .
Luke
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
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();
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
try{
String line = in.readLine();
if (line.contains("TIME")){
dataOutputStream.writeUTF("TIME IS....."); // ITS HERE THE PROBLEM MAY BE ?
{
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
}
} 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();
}
}
}
}
}
}
The Android Client
UPDATE , i think the problem is with the client only being connected when you send a message. How do i have a reading loop in here that wont affect when i send data out from the client.
package com.exercise.AndroidClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidClient 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);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.101", 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
e.printStackTrace();
} 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 (dataOutputStream != null){
try {
dataOutputStream.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();
}
}
}
}};
}
After the dataOutputStream.writeUTF() line, write dataOutputStream.flush();. That will send all the data through.
It seems you’re reading from the stream to output the message.
System.out.println("message: " + dataInputStream.readUTF());
So the command has been removed from the stream when you try to run
String line = in.readLine();
You should try to read the command from the stream into a variable before outputting the message and then check if that string contains "TIME".
Also why use two different methods to read from the stream? You could just use the BufferedReader and discard DataInputStream. You could as well use PrintWriter instead of DataOutputStream.
Something like this:
out = new PrintWriter( socket.getOutputStream(), true );
and then:
out.println( "Time is..." );
Hope this helps.

Java Sockets - transmission in real time

i got this code form Android-er blogspot, big thanks for him to make me almost understand basic socket connections in java. So i got this client app on my android device, and computer with server running, but how could i make a loop in a client code, to make it send data from EditText in real time? (whenever it changes) Please if someone could clear it out for a complete newbie?
-----This is client code (Android-er Copyrights):
package com.exercise.AndroidClient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidClient 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);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("192.168.1.101", 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
e.printStackTrace();
} 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 (dataOutputStream != null){
try {
dataOutputStream.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();
}
}
}
}};
}
-----This is server code (Android-er Copyrights):
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
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());
dataOutputStream.writeUTF("Hello!");
} 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();
}
}
}
}
}
}
There are a few things you will need to change.
First of all, if you want the data to be sent in real time, you will need to change from using a Button OnClickListener to using a TextWatcher (see addTextChangedListener in TextView)
As this event will be fired every time the text changes, you will need to open your socket outside of the event (you don't want a new socket each time some text is typed), and then in your listener, you just want to send the new data down the socket.
You can set a text changed listener on your EditText and do the sending from there.
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
// ... do your sending here
}
But beware that if that sending is not asynchronous, it may block text entry for the user. Network latency can be relatively high on GSM networks, so the user may be irritated, when his freshly typed characters will not immediately appear on screen.

Categories