Using AsyncTask for android network connection - java

I am having some trouble using AsyncTask as I have never come across it before and have no clue what I am doing with it.
Basically I am getting a force close because I am trying to run the connection on a main class. Could someone possibly help me with adding AsyncTask into the code:
package com.smarte.smartipcontrol;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class IPControl extends Activity {
private Socket socket;
private String serverIpAddress;
private static final int REDIRECTED_SERVERPORT = 32;
public PrintWriter out;
public BufferedReader in ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
serverIpAddress = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
createConnection();
}
public void getModel(View view) {
try {
out.println("[m\r\n");
//System.out.print("root\r\n");
while (! in .ready());
String textStatus = readBuffer();
} catch (IOException e) {}
}
public void createConnection() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
//System.out.print("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
//System.out.print("root\r\n");
while (! in .ready());
readBuffer();
} catch (IOException e) {}
//R.id.textStatus
}
private String readBuffer() throws IOException {
String msg = "";
while ( in .ready()) {
msg = msg + (char) in .read();
}
//System.out.print(msg);
if (msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else return msg;
}
}

Go through this simple tutorial to get a good grounding on what an AsyncTask is and how to use it:
https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
Then try modifying your code to use async tasks. If you get problems, Just come back here :-)

Just one quick example of how it migtht look like:
public class IPControl extends Activity {
private ProgressDialog pd = null;
private String data = null;
private Socket socket;
private String serverIpAddress;
private static final int REDIRECTED_SERVERPORT = 32;
public PrintWriter out;
public BufferedReader in ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
this.pd = ProgressDialog.show(this, "Loading..", "Please Wait...", true, false);
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected Void doInBackground(String... args) {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in.ready());
readBuffer();
out.println("root\r\n");
//System.out.print("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
//System.out.print("root\r\n");
while (! in .ready());
String msg = "";
while (in.ready()) {
msg = msg + (char) in .read();
}
} catch (IOException e) {}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//resultis the data returned from doInbackground
IPControl.this.data = result;
if (IPControl.this.pd != null) {
IPControl.this.pd.dismiss();
}
}
}

By checking the documentaion here..
You need to put the create connection part in the doInBackground.. then in the onPostExecute do whatever you want to update the ui.

Related

Reconnecting to Bluetooth in android / Reading after Reconnect

I have a program that establishes a Bluetooth connection, reads the InputStream to a textView, and can disconnect from the module. While I can successfully disconnect and reconnect to the module (HC-05) as many times as I please, I can't get an InputStream read anymore after I reconnect. I believe it is because I don't know how to reinitialize the thread I'm using to read the InputStream. I am very new to java and android programming, any help with this issue would be appreciated.This is my code:
The textView for the read display is called 'Status' and I am hoping to "reset" the thread upon the onclick connect().
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements Runnable {
private BluetoothAdapter adapter;
private InputStream inputStream;
private OutputStream outputStream;
private Thread thread;
private TextView Status;
private TextView Connection;
private BluetoothSocket socket = null;
private boolean threadStatusInitial=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Status=(TextView) findViewById(R.id.StatusID);
Connection=(TextView) findViewById(R.id.ConnectionStatus);
adapter= BluetoothAdapter.getDefaultAdapter();
if(adapter==null){
Toast.makeText(this,"bluetooth is unavailable",Toast.LENGTH_SHORT).show();
finish();
return;
}
thread=new Thread(this);
}
public void connect(View view){
Set<BluetoothDevice> devices=adapter.getBondedDevices();
for(BluetoothDevice device:devices){
if(device.getName().startsWith("HC-05")){
try {
socket=device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
socket.connect();
Connection.setText("Connected");
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
if (threadStatusInitial){
thread.start();
threadStatusInitial=false; //this ensures that the thread.start() method will only be called during the first connection
}
} catch (IOException e) {
Toast.makeText(this,"Can't Connect",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
}
}
}
public void Disconnect(View view) throws InterruptedException {
if (inputStream != null) {
try {inputStream.close();} catch (Exception e) {}
inputStream = null;
}
if (outputStream != null) {
try {outputStream.close();} catch (Exception e) {}
outputStream = null;
}
if (socket != null) {
try {socket.close();} catch (Exception e) {Toast.makeText(this,"Can't Connect",Toast.LENGTH_LONG).show();}
socket = null;
}
Connection.setText("Disconnected");
}
#Override
public void run() {
String textInput = "hi";
byte[] writeBytes=textInput.getBytes();
if(outputStream!=null){
try {
outputStream.write(writeBytes);
} catch (IOException e) {
Toast.makeText(this,"Unable to Write to Bluetooth ",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
while(inputStream!=null){
byte [] buffer=new byte[2048];
try {
int length=inputStream.read(buffer);
final String strReceived = new String(buffer, 0, length);
runOnUiThread(new Runnable(){
#Override
public void run() {
Status.setText(strReceived);
}});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Can't send message over hotspot, using TCP connection. Android

I'm creating an simple app, in which I want to send message over local wifi connection using TCP. So I'm creating hotspot on one device and connect it from other device.
Now, on hosting device, I'm running following server application and on connecting device I'm running client application.
But nothing happens when I press send button on client device. My code for both server and client is as following:
Code for server:
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
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() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
Code for client:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket socket;
private String TAG="XXX";
private static final int SERVERPORT = 5000;
private String SERVER_IP ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
SERVER_IP = getWifiApIpAddress();
}
public String getWifiApIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
if (intf.getName().contains("wlan")||intf.getName().contains("ap")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& (inetAddress.getAddress().length == 4)) {
Log.d(TAG, inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
// out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I'm following this tutorial. As explained there, It is working fine in android emulators. But doesn't work on actual devices.
So I thought the IP address should be given different on different hotspots. So I've written a method in client code to get server hotspot's IP address and than connect to it. But still nothing happens on pressing send button.
So, What am I missing here? Is my method correct? Is there any mistakes in port numbers?
In the tutorial, author is doing something called port forwarding. What about port forwarding for actual devices?
I've searched everywhere for this on Internet but can't find any exact solution or any tutorial explaining this type of application. Please help me!
EDIT:
when I run this in real devices, It is giving NllPointerException in clients code, on following line:
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
You don't need to forward anything on device, just make sure your device is on the same network & use the port you have hard-coded or defined in the settings.
We forward port in emulator because its running on your host machine & we are telling the host to forward traffic coming on that specific port to emulator, since in an actual device you don't need to do that so you just to have to make sure your device is on the same network & correct port is being called.

How to run TCP connection on real android device?

I'm following this tutorial for creating an app with server-client chat. It is working like a charm in android emulators as described there. But I want to simulate it on my device. What about port forwarding in real devices?
I've tried connecting my two devices in a single hotspot and sending message. But it is not working. Do I need to change some code for that? or there is other method out there?
Any help will be appreciated!
I'm new to networking and android both.
Server code:
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
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() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
Client code:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}

IOException java.net.ConnectException: failed to connect to /127.0.0.1(port 5000):connect failed:ECONNREFUSED(Connection Refused)

Trying to do android socket programming based on this tutorial
http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/
I have my firewall turned off and anti virus disabled. If I make my server address to 127.0.0.1 I get the error in the title. If I make it my local IP address,it just sits at socket going to be created.I have tried it without and with port forwarding and setting it to the same port.
Client
package com.bennatpjose.androidsocketclient;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private Socket socket;
private TextView text;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.52.7.179";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
text.setText(text.getText().toString()+"Client Thread should be fired");
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
text.setText(text.getText().toString()+"\n"+"Click Event "+str);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
text.setText(text.getText().toString()+"\n"+"Next is out.println("+str+")");
out.println(str);
text.setText(text.getText().toString()+"\n"+"out.println("+str+")");
} catch (UnknownHostException e) {
text.setText(text.getText().toString()+"\nPrint Writer UnknownHostException "+e.toString());
} catch (IOException e) {
text.setText(text.getText().toString()+"\nPrint Writer IOException "+e.toString());
} catch (Exception e) {
text.setText(text.getText().toString()+"\nPrint Writer Exception "+e.toString());
}
}
class ClientThread implements Runnable {
#Override
public void run() {
text.setText(text.getText().toString()+"\nInside client thread run method ");
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
//If I set address to my local ip it just sits here and doesn't show socket created.
text.setText(text.getText().toString()+"\n"+serverAddr +" Socket going to be Created");
socket = new Socket(serverAddr, SERVERPORT);
text.setText(text.getText().toString()+"\n"+socket.toString() +"Socket Created");
} catch (UnknownHostException e1) {
text.setText(text.getText().toString()+"\nClient Thread UnknownHostException "+e1.toString());
} catch (IOException e1) {
text.setText(text.getText().toString()+"\nClient Thread IOException "+e1.toString());
}catch (Exception e1) {
text.setText(text.getText().toString()+"\nClient Thread Exception "+e1.toString());
}
}
}
}
Server
package com.bennatpjose.androidsocketserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text2);
text.setText(text.getText().toString()+"onCreate method started");
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
text.setText(text.getText().toString()+"\n"+"serverThread started");
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
text.setText("!!Socket Stopped!!");
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
text.setText(text.getText().toString()+socket+"\n");
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
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() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
So I figured it out. One of the mistakes I did was replacing the SERVER_IP with my local ip where as I should have left it at 10.0.2.2 since its a special loopback address android emulators.
10.0.2.2 Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
You also have to run the server first,set the port redirection and then run the client.
Look up Emulator networking section at http://developer.android.com/tools/devices/emulator.html

How to open a socket from an android phone without getting a SocketException run time error?

I am trying to write an app on android where, there is a multithreaded server running on a computer and in the app on the phone there is a button, once the user clicks that button a socket is opened between the server and the client. My problem is that once the user clicks that button I get a lot of runtime errors on my log cat. One of them is SocketException socket failed (Permission denied)
Here is the code for the activity that has the button that opens the socket with the server
package guc.edu.eg;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Activity1 extends Activity {
Button start;
Button help;
Button credentials;
Socket socket;
//public DataInputStream in=null;
public PrintStream out=null;
InetAddress IP;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
//try {
//IP = InetAddress.getLocalHost();
//} catch (UnknownHostException e) {
// //TODO Auto-generated catch block
//e.printStackTrace();
//}
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
socket= new Socket("127.0.0.1",4444);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//try {
//out = new PrintStream(socket.getOutputStream());
//out.println ("The socket is open at the phone!!");
//} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
//}
//try {
// in = new
//DataInputStream(socket.getInputStream());
// } catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
//}
Intent intent = new Intent(Activity1.this,Activity2.class);
startActivity(intent);
}
});
help = (Button) findViewById(R.id.help);
help.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Activity1.this,Activity3.class);
startActivity(intent);
finish();
}
});
credentials = (Button) findViewById(R.id.credentials);
credentials.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Activity1.this,Activity4.class);
startActivity(intent);
finish();
}
});
}
}
Here is the code for the Server class, that is actually placed in a different project other than the one that has the app code.
import java.io.*;
import java.net.*;
import java.util.LinkedList;
// Java extension packages
public class Server implements Runnable {
ServerSocket serverSocket;
Socket clientSocket;
int portNo;
LinkedList<ServerThread> allClients = new LinkedList<ServerThread>();
public Server(int port) {
portNo = port;
}
public void run() {
try {
serverSocket = new ServerSocket(portNo);
while (true) {
clientSocket = serverSocket.accept();
ServerThread x = new ServerThread(clientSocket, this);
allClients.add(x);
x.start();
}
} catch (EOFException eofException) {
System.out.println("Client terminated connection");
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public void sendMessageToClient(String message) {
String[] x = message.split(",");
//for (int i = 0; i < allClients.size(); i++) {
//if (allClients.get(i).clientName.equals(x[2])) {
//allClients.get(i).sendMessage(x[1] + ": " + x[0]);
//return;
//}
//}
// if you didn't return then you couldn't reach your destination in your local server
// send the message to the network server to search for it
}
public String getLocalClientsNames() {
String names = "";
for (int i = 0; i < allClients.size(); i++) {
names += allClients.get(i).clientName + ",";
}
return names;
}
public void sendClientNamesToAll() {
//net.sendAllClientNames();
}
public static void main(String [] args) {
Server server = new Server(4444);
new Thread(server).start();
}
}
Here is the ServerThread class placed at the same package with the Server class
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ServerThread extends Thread {
private Socket clientSocket;
private Server server;
String clientName;
private ObjectOutputStream output;
private ObjectInputStream input;
public ServerThread(Socket client, Server s) {
this.clientSocket = client;
this.server = s;
}
#Override
public void run() {
try {
output = new ObjectOutputStream(clientSocket.getOutputStream());
output.flush();
input = new ObjectInputStream(clientSocket.getInputStream());
processConnection();
closeConnection();
} catch (IOException e) {
System.out.println("in or out failed");
}
}
private void processConnection() throws IOException {
String message = "!!";
System.out.println("mada5alsh el while");
while (!message.equalsIgnoreCase("Client>> end")) {
try {
System.out.println("da5al el while");
message = (String) input.readObject();
System.out.print(message);
if (message.equalsIgnoreCase("Name")) {
clientName = (String) input.readObject();
server.sendClientNamesToAll();
} else {
server.sendMessageToClient(message);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public void closeConnection() throws IOException {
output.close();
input.close();
clientSocket.close();
}
public void sendMessage(String message) {
try {
output.writeObject(message);
output.flush();
} catch (IOException ioException) {
//do
}
}
}
I think it might be something that has to do with the manifest file so I added this line of code to it
`<uses-permission android:name="android.permission.INTERNET"></uses-permission>`
You create your client socket in the main thread which is not permitted.
Use a separate thread or use AsyncTask.
Adding <uses-permission android:name="android.permission.INTERNET"></uses-permission> to you AndroidManifest.xml should do the trick.

Categories

Resources