How to make a consistent WIFI connection in android - java

In my new android app, I have made a direct tcp connection to a device with specific IP and port, all working fine. Issue here is when Wifi disconnect it does not reconnect or send data again.
Inside my code below, I have a class Client.java and MainActivity.java below.
How can I do this?
#####################################################
public class Client extends AsyncTask<String, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
Socket socket = null; Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse = textResponse;
}
#Override
protected Void doInBackground(String... params) {
String str = params[0];
try {
smtpSocket = new Socket(dstAddress, dstPort);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = smtpSocket.getInputStream();
//smtpSocket.
/* 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");
}
//textResponse.setText(response);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
if (smtpSocket != null && os != null ) {
try {
os.writeBytes(str);
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}
//os.close();
//is.close();
//smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IO-Exception: " + e);
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//textResponse.setText("dweewed");
super.onPostExecute(result);
//super.cancel(true);
}
public void sendToPort(String str) throws IOException {
if (smtpSocket != null && os != null ) {
try {
os.writeBytes(str);
// os.close();
// is.close();
// smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}
#############################################################
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button buttonConnect, buttonClear;
TextView response;
Client myClient;
String editTextAddress = "10.0.1.50";
Integer editTextPort = 48;
boolean keepalive = true;
ConnectivityManager connManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myClient = new Client(editTextAddress, editTextPort, response);
connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
buttonConnect = (Button) findViewById(R.id.btnconnect);
buttonClear = (Button) findViewById(R.id.clear);
response = (TextView) findViewById(R.id.feedback);
buttonConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
response.setText("");
String dat = "Open";
try {
//String dat = "sec rfdgdf";
dat = dat + "\r\n";
myClient.sendToPort(dat);
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
response.setText("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
});
}
#Override
public void onResume(){
super.onResume();
response.setText("Resum`enter code here`e connected!");
}
}

You can implement the reconnect logic in the callback of registerNetworkCallback in the ConnectivityManager
The code you provided doesn't use connManager

Related

Android Sockets not working in reality

I am trying to connect an Android device to a java server. It works perfectly when I use the emulator but when I port it onto my phone there is no connection.
The aim of the code is to send a value from client to server, perform a calculation on it and return it back to the client to be displayed.
This is my server code:
public class ServerTest {
public static final int PORT_NUMBER = 8000;
protected Socket socket;
private ServerTest(Socket socket) {
this.socket = socket;
System.out.println("New client connected from " + socket.getInetAddress().getHostAddress());
connect();
}
public void connect() {
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String request = br.readLine();
if (request.equals("end")) {
System.out.println("Message received: " + request + ". Ending connection.");
request = "End Connection";
out.write(request.getBytes());
in.close();
out.close();
socket.close();
System.exit(0);
} else {
System.out.println("Message received: " + request);
request = calculatePi(request);
System.out.println("Output: " + request);
out.write(request.getBytes());
}
} catch (IOException ex) {
System.out.println("Unable to get streams from client");
} finally {
try {
in.close();
out.close();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("Welcome. IP address is: " + getIP());
ServerSocket server = null;
try {
server = new ServerSocket(PORT_NUMBER);
while (true) {
new ServerTest(server.accept());
}
} catch (IOException ex) {
System.out.println("Unable to start server.");
} finally {
try {
if (server != null)
server.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static String getIP() {
String ip = "";
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
// *EDIT*
if (addr instanceof Inet6Address) continue;
ip = addr.getHostAddress();
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
return ip;
}
and this is my client side code on device:
public class MainActivity extends AppCompatActivity {
TextView piResultTextView;
EditText addressEditText, messageEditText;
Button connectButton;
Handler handler = new Handler();
Results results;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
results = new Results();
addressEditText = findViewById(R.id.AddressEditText);
messageEditText = findViewById(R.id.MessageEditText);
connectButton = findViewById(R.id.ConnectButton);
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connect();
}
});
piResultTextView = findViewById(R.id.PiResultTextView);
}
public void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
String hostAddress = addressEditText.getText().toString();
int port = 8000;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(hostAddress, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(), "Unknown host: " + hostAddress, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to get streams from server", Toast.LENGTH_SHORT).show();
}
String input = messageEditText.getText().toString();
try {
out.println(input);
results.pi = in.readLine();
handler.post(new Runnable() {
#Override
public void run() {
piResultTextView.setText(results.pi);
}
});
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to read input stream from server", Toast.LENGTH_SHORT).show();
}
try {
out.close();
in.close();
echoSocket.close();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error closing streams", Toast.LENGTH_SHORT).show();
}
}
});
thread.start();
}
}

Server Ip at Client side using Sockets

I need to create an application using android socket level programming, I created a connection between server and client but I need to show waiting server IP list at client side and select one IP from the list and establish a connection between them.
Here is my code for server side
public class Server extends AppCompatActivity {
private static final String TAG = "ServerActivity";
private TextView tvServerStatus;
private TextView recievemsg;
InetAddress receiverAddress;
public static String SERVERIP = "";
DatagramSocket datagramSocket;
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
Handler updateConversationHandler;
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
updateConversationHandler = new Handler();
tvServerStatus = (TextView) findViewById(R.id.tvServerStatus);
recievemsg=(TextView)findViewById(R.id.send_msg);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = "0123456789".getBytes();
byte[] address=SERVERIP.getBytes();
receiverAddress = InetAddress.getByAddress(address);
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, receiverAddress, 8080);
datagramSocket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getLocalIpAddress() {
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;
}
public class ServerThread implements Runnable {
#Override
public void run() {
try {
Log.e(TAG, "Server IP: " + SERVERIP);
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Listening On Ip: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (!Thread.currentThread().isInterrupted()) {
{
try {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(client);
new Thread(commThread).start();
// Log.e(TAG, "Client Socket: " + client);
// new Clients_Handle(client, ROOT_DIRECTORY).start();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
recievemsg.setText(recievemsg.getText().toString() + "Client Says: " + msg + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
Log.e(TAG,"Socket Closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is my client side code
public class Clientss extends AppCompatActivity {
private static final String TAG = "Client_Activity";
private EditText etServerIp;
private EditText etMsg;
private Button btnConnectClients;
private Button btnSendMsg;
private TextView textIn;
private String serverIpAddress = "";
private String t;
private boolean connected = false;
DatagramSocket datagramSocket;
DatagramPacket packet;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clientss);
Log.e(TAG, "ONCREATE METHOD");
textIn = (TextView)findViewById(R.id.txt_msg);
initializations();
eventClickListener();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = new byte[10];
packet = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(packet);
byte[] buff = packet.getData();
textIn.setText(buff.toString());
System.out.println("this is incoming ip"+buff.toString());
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// textIn.setText(t);
}
private void eventClickListener() {
btnConnectClients.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = etServerIp.getText().toString().trim();
connectsClient();
}
}
});
btnSendMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = etMsg.getText().toString().trim();
ClientResponseTask clientResponseTask=new ClientResponseTask(msg);
clientResponseTask.execute();
}
});
}
private void connectsClient() {
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
private void initializations() {
etServerIp = (EditText) findViewById(R.id.etServerIp);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSendMsg = (Button) findViewById(R.id.btnMsgSend);
btnConnectClients = (Button) findViewById(R.id.btnConnect);
}
private class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.e(TAG, "C: Connecting...");
socket = new Socket(serverAddr, Server.SERVERPORT);
System.out.println("this is socket"+socket);
connected = true;
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
//showToast("");
Log.e(TAG, "C: Connected..." + socket);
} catch (Exception e) {
Log.e(TAG, "C: Error", e);
connected = false;
}
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.arg1 == 1)
Toast.makeText(getApplicationContext(),"Connected...", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onDestroy() {
if (socket != null) try {
socket.close();
Log.e(TAG, "C: Socket Closed.");
} catch (IOException e) {
e.printStackTrace();
} finally
{
try
{
socket.close();
}
catch(Exception e){}
}
super.onDestroy();
}
protected class ClientResponseTask extends AsyncTask<Void,Void,Void> {
String msg;
ClientResponseTask(String msg){
this.msg=msg;
}
#Override
protected Void doInBackground(Void... params) {
if (connected) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(msg);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
else {
connectsClient();
}
return null;
}
}
}
Please help me to find a solution.

Android - Passing simple string over Wi-fi?

I have Wi-fi direct demo. In that we can transfer any image files to other devices. When another device get connected and it shows to send image from gallery. And at other side it shows sent image. But I want to send a simple string and at other side I want to toast that string. Here I am posting a code in which they have implemented file transfer. I am very confused in this code. I am not getting where to change to pass only string. Please help me. Thanks.
DeviceDetailFragment.java
/**
* A fragment that manages a particular peer and allows interaction with device
* i.e. setting up network connection and transferring data.
*/
public class DeviceDetailFragment extends Fragment implements ConnectionInfoListener {
protected static final int CHOOSE_FILE_RESULT_CODE = 20;
private View mContentView = null;
private WifiP2pDevice device;
private WifiP2pInfo info;
ProgressDialog progressDialog = null;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.device_detail, null);
mContentView.findViewById(R.id.btn_connect).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel",
"Connecting to :" + device.deviceAddress, true, true
// new DialogInterface.OnCancelListener() {
//
// #Override
// public void onCancel(DialogInterface dialog) {
// ((DeviceActionListener) getActivity()).cancelDisconnect();
// }
// }
);
((DeviceActionListener) getActivity()).connect(config);
}
});
mContentView.findViewById(R.id.btn_disconnect).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
((DeviceActionListener) getActivity()).disconnect();
}
});
mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Allow user to pick an image from Gallery or other
// registered apps
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
}
});
return mContentView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using
// FileTransferService.
Uri uri = data.getData();
TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
statusText.setText("Sending: " + uri);
Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
getActivity().startService(serviceIntent);
}
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
this.info = info;
this.getView().setVisibility(View.VISIBLE);
// The owner IP is now known.
TextView view = (TextView) mContentView.findViewById(R.id.group_owner);
view.setText(getResources().getString(R.string.group_owner_text)
+ ((info.isGroupOwner == true) ? getResources().getString(R.string.yes)
: getResources().getString(R.string.no)));
// InetAddress from WifiP2pInfo struct.
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
// After the group negotiation, we assign the group owner as the file
// server. The file server is single threaded, single connection server
// socket.
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text))
.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the
// get file button.
mContentView.findViewById(R.id.btn_start_client).setVisibility(View.VISIBLE);
((TextView) mContentView.findViewById(R.id.status_text)).setText(getResources()
.getString(R.string.client_text));
}
// hide the connect button
mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}
/**
* Updates the UI with device data
*
* #param device the device to be displayed
*/
public void showDetails(WifiP2pDevice device) {
this.device = device;
this.getView().setVisibility(View.VISIBLE);
TextView view = (TextView) mContentView.findViewById(R.id.device_address);
view.setText(device.deviceAddress);
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText(device.toString());
}
/**
* Clears the UI fields after a disconnect or direct mode disable operation.
*/
public void resetViews() {
mContentView.findViewById(R.id.btn_connect).setVisibility(View.VISIBLE);
TextView view = (TextView) mContentView.findViewById(R.id.device_address);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.device_info);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.group_owner);
view.setText(R.string.empty);
view = (TextView) mContentView.findViewById(R.id.status_text);
view.setText(R.string.empty);
mContentView.findViewById(R.id.btn_start_client).setVisibility(View.GONE);
this.getView().setVisibility(View.GONE);
}
/**
* A simple server socket that accepts connection and writes some data on
* the stream.
*/
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
private TextView statusText;
/**
* #param context
* #param statusText
*/
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
statusText.setText("Opening a server socket");
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime=System.currentTimeMillis();
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime=System.currentTimeMillis()-startTime;
Log.v("","Time taken to transfer all bytes is : "+endTime);
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
}
FileTransferService.java
/**
* A service that process each file transfer request i.e Intent by opening a
* socket connection with the WiFi Direct Group Owner and writing the file
*/
public class FileTransferService extends IntentService {
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public FileTransferService(String name) {
super(name);
}
public FileTransferService() {
super("FileTransferService");
}
/*
* (non-Javadoc)
* #see android.app.IntentService#onHandleIntent(android.content.Intent)
*/
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
}
DeviceDetailFragment.copyFile(is, stream);
Log.d(WiFiDirectActivity.TAG, "Client: Data written");
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
}
You can do something like this:
DeviceDetailFragment.java
#Override
protected String doInBackground(Void... params) {
ServerSocket serverSocket = null;
Socket client = null;
DataInputStream inputstream = null;
try {
serverSocket = new ServerSocket(8988);
client = serverSocket.accept();
inputstream = new DataInputStream(client.getInputStream());
String str = inputstream.readUTF();
serverSocket.close();
return str;
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}finally{
if(inputstream != null){
try{
inputstream.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(client != null){
try{
client.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(serverSocket != null){
try{
serverSocket.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(..., result, ...).show();;
}
}
FileTransferService.java
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
DataOutputStream stream = null;
try {
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
stream = new DataOutputStream(socket.getOutputStream());
stream.writeUTF("a string");
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}

cannot print the value taken from socket connection

public class MyClientTask extends AsyncTask<String, String, String> {
String dstAddress;
int dstPort;
MyClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
protected String doInBackground(String... arg0) {
String response = "";
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((response = stdIn.readLine()) != null) {
Log.i("response", response);
publishProgress(response);
}
Log.i("response", response);
} catch (UnknownHostException e) {
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onProgressUpdate(String... values) {
Log.i("prama", values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
I write above code to read value from socket.when i start the async task the value will be print on the log as i do in doInbackground but my toast message will not be fired after the async task finished.

Unable to establish socket connect between two different android devices at different locations with different service providers

I am trying to establish a socket connection between two different devices at different places. I am using Airtel SIM on my android device. I am running following code on the device:
public class MainActivity extends Activity
{
Context context;
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
Sql s = new Sql(context);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
new GetPublicIPTask().execute();
}
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("Port: " + serverSocket.getLocalPort());
}
});
while (true)
{
Socket socket = null;
try
{
socket = serverSocket.accept();
}
catch (Exception e)
{
e.printStackTrace();
}
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)
{
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 client " + cnt;
try
{
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replied: " + msgReply + "\n";
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText(message);
}
});
}
catch (IOException e)
{
e.printStackTrace();
message += "Exception! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText(message);
}
});
}
}
public class GetPublicIPTask extends AsyncTask<String, Integer, String>
{
ProgressDialog progressDialog;
String serverResponse = "";
public GetPublicIPTask()
{
progressDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute()
{
if (!NetWorkInfo.isOnline(context))
{
Toast.makeText(context, "No Internet Connection", Toast.LENGTH_LONG).show();
return;
}
progressDialog.setMessage("Getting IP");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... sUrl)
{
BufferedReader in = null;
int TIME_OUT = 1000 * 60 * 10;
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
HttpConnectionParams.setSoTimeout(params, TIME_OUT);
HttpGet httppost = new HttpGet("http://checkip.dyndns.org");
httppost.setHeader("Content-Type", "application/json");
try
{
HttpResponse response = httpclient.execute(httppost);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null)
{
sb.append(line);
}
serverResponse = sb.toString();
return serverResponse;
}
catch (Exception ex)
{
Log.d("Socket Server", "StackTrace : " + ex.getStackTrace().toString());
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
return null;
}
#Override
protected void onPostExecute(String result)
{
if (progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
infoip.setText(serverResponse);
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
super.onPostExecute(result);
}
}
}
And from terminal I am hitting the mobile app:
telnet publicIpAddress 8080
Same process working in local network, but not working in mobile networks.

Categories