Socket not connected in my Android app - java

I've been working in a server/client application that needs to get the hour from a server working in my computer.
When I try to run this app in my phone it says that SOCKET NOT CONNECTED. I tried everything but it still not working.
The thread is working, but the socket is not connecting!
The permissions I used:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The MainActivity.java is:
package com.example.clientehora;
/* imports */
public class MainActivity extends Activity {
Socket socket = new Socket();
String SERVER_IP = "10.215.19.41";
int SERVERPORT = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
#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;
}
public void ejecutar(View view) {
try {
System.out.println("Hola amigo, si me presionaste! =D" + socket.getInetAddress() + socket.getPort());
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String cadena = br.readLine();
System.out.println("LA CADENA ES: " +cadena);
EditText et = (EditText)findViewById(R.id.fecha);
et.setText(cadena);
br.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
System.out.println("Se ha conectado sin problemas");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}

This works for me to connect to my Win7 PC via USB (mTimeout is 5000):
mSocket = new Socket();
mSocket.setSoTimeout(mTimeout);
mSocket.connect(new InetSocketAddress(SERVER_IP, SERVERPORT), mTimeout);
I get the IP to use using this command on the PC:
InetAddress.getLocalHost().getHostAddress()

Related

Android and java bluetooth client server app

I have an android app. I want to send a string to java server when I touch the button each time in my client app.I am able to connect to server.
But the problem is when I touch the button, no string is sending to server. No matter how many times I touch the button the string is not sending but suddenly when I exit the app in my smartphone, means when I destroy the activity, all the strings then transfers to the server at the same time.
If I touch the button 100 times, 100 same strings are transferred to the server only when I destroy activity. I want the string to be transferred to server at the time when I touch the button.
Please help me with this. I am a newbie. My code is below:
public class Joystick extends Activity {
BluetoothAdapter ba=BluetoothAdapter.getDefaultAdapter();
//local bluetooth adapter object created
BluetoothDevice bd; //GLOBAL DECLARATION BLOCK
BluetoothSocket bs;
OutputStream os;
InputStream in;
Button up;
private static final UUID MY_UUID =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.joystick);
up= (Button) findViewById(R.id.up);
if(ba.isEnabled()==false) //BLUETOOTH ADAPTER ENABLED IF WAS DISABLED
ba.enable();
final String address = getIntent().getStringExtra("address").trim();
setResult(100, new Intent());
bd=ba.getRemoteDevice(address);
BluetoothConnect.start();
}
#Override
protected void onResume(){
super.onResume();
up.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
try {
os = bs.getOutputStream();
String message = "up";
byte[] msgBuffer = message.getBytes();
os.write(msgBuffer);
} catch (IOException e) {
e.printStackTrace();
}
break;
case MotionEvent.ACTION_UP:
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
return true;
}
});
}
Thread BluetoothConnect = new Thread(){
public void run(){
try {
bs=bd.createRfcommSocketToServiceRecord(MY_UUID);
bs.connect();
} catch (IOException e) {
try {
bs.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
};
protected void onStop(){
super.onStop();
try {
os.close();
bs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (os != null) {
try {
os.flush();
} catch (IOException e) {
}
}
}}
the server code is:
public class SimpleSPPServer {
private static Robot robot;
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=SampleSPPServer";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: "+dev.getBluetoothAddress());
System.out.println("Remote device name: "+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
try{
robot=new Robot();
if(lineRead.equalsIgnoreCase("up")){
robot.keyPress(KeyEvent.VK_UP);
robot.keyRelease(KeyEvent.VK_UP);
} }
catch(AWTException e){
System.out.println("exception while creating robot instance");
}
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write("Response String from SPP Server\r\n");
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
SimpleSPPServer sampleSPPServer=new SimpleSPPServer();
sampleSPPServer.startServer();
}
}
Problem solved.. Just add "\n" at the end of string you want to transfer.

Java Android Client Socket not working

Am I missing something. I've checked other posts and have thses set in my manifest.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Whenever I try to create a new socket on Samsung Galaxy Express it never gets past this line.
Socket s = new Socket("10.0.2.2", 4736);
This is my class for starting a socket in a runnable.
private class SendThread implements Runnable {
#Override
public void run() {
try {
Socket s = new Socket("10.0.2.2", 4736); <---never gets past this
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
out.println(sendString);
new BufferedReader(new InputStreamReader(s.getInputStream()));
Log.d(TAG, "sent");
s.close();
} catch (Exception e) {
Log.d(TAG, "error");
e.printStackTrace();
}
Log.d(TAG, "end");
}
}
Server Socket
private class ReceiveThread implements Runnable {
private ServerSocket receiverSocket;
private BufferedReader input;
private Socket socket = null;
public void run() {
try {
receiverSocket = new ServerSocket(receivePort);
receiverSocket.setReuseAddress(true);
while (killConnection == false) {
Log.d(TAG, "listening");
socket = receiverSocket.accept();
this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
Log.d(TAG, "Input from server" + input.toString());
String s = input.readLine();
//UpdateUi(s);
socket.close();
}
receiverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Ok yes the server-side socket isn't listening

Android 2-Way TCP/IP ServerSocket/Socket Communication

Using this great tutorial by the Java Code Geeks, I am easily able to create a client activity that sends data via TCP to a server's port 4000 using the following code:
public class Client 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.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();
}
}
}
}
Then using their other snippet for the server activity I can catch messages using TCP on that port:
public class Server 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);
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");
}
}
}
My question is how can I make it so these 2 can communicate back and forth?
Android -> Server(4000) -> Android(4001)?
In other words how can I make my app help the device act as both the client (sending out data to another device on port 4000) and the server (listening for data on port 4001) at the same time?
On the Server side change the port to 5000 (same as Client) instead of 6000:
And you need to update the following class because you don't want to create a new socket, you should use the one already created (in the Client part).
NB: the socket given as an argument to CommunicationThread is the socket that you supposedly already created (Client part).
class ServerThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
}
}

Unable to connect to server through wifi in android

I am trying to connect one android device to another using wifi. One device is acting as a server using hotspot. Another device is connected to it. But when I am running the following piece of code, it gives the following exception.
java.net.ConnectException: failed to connect to /192.168.43.198 (port 5555): connect failed: ENETUNREACH (Network is unreachable)
I am using the below files.
HostActivity.java
public class HostActivity extends Activity {
ListView lvHost;
HostAdapter adHost;
final String HostTAG = "Host1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_host);
WifiManager wifiManager = (WifiManager)this.getSystemService (Context.WIFI_SERVICE);
new RetrieveFeedTask2(getApplicationContext()).execute("");
int i =0 ;
lvHost = (ListView) findViewById( R.id.lvHost);
int j = 0;
ArrayList<WifiConfiguration> list = (ArrayList<WifiConfiguration>) wifiManager.getConfiguredNetworks();
adHost = new HostAdapter(list,this);
lvHost.setAdapter(adHost);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.host, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
class RetrieveFeedTask2 extends AsyncTask<String, Context, String> {
Context ctx = null;
public RetrieveFeedTask2(Context Dctx) {
// TODO Auto-generated constructor stub
ctx = Dctx;
}
protected String doInBackground(String ...url) {
final String HostTAG = "Host1";
final WifiManager wifiManager = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE);
try {
Boolean end = false;
Log.i("test","HostRun");
ServerSocket ss = new ServerSocket(5555);
while(!end){
Log.i("test", "HostRun2");
//Server is waiting for client here, if needed
Socket s = ss.accept();
Log.i("test", "HostRun3");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
Log.i("test", "From client: "+st);
System.out.println("From client: "+st);
//output.println("Good bye and thanks for all the fish :)");
s.close();
// ArrayList<WifiConfiguration> list = (ArrayList<WifiConfiguration>) wifiManager.getConfiguredNetworks();
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.i("test","host unknown");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
ClientActivity.java
public class ClientActivity extends Activity {
final String ClientTAG = "Client1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
WifiManager wifiManager = (WifiManager)getSystemService("wifi");
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = Formatter.formatIpAddress(ipAddress);
new RetrieveFeedTask().execute(ip);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
}
class RetrieveFeedTask extends AsyncTask<String, String, String> {
//Context context;
protected String doInBackground(String ...urls) {
final String ClientTAG = "Client1";
InetAddress ia=null;
Log.i("test", "ClientRun1");
try {
try {
ia=InetAddress.getLocalHost();
Log.i("test",ia.toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Socket s = new Socket("192.168.43.198",5555);
Log.i("test", "ClientRun");
//outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("Hello Android!");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
//read line(s)
String st = input.readLine();
//. . .
//Close connection
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
I tried googling. Many have mentioned same problem and I tried all the solutions but still not able to connect. Please help.
Some suggestions:
Use 10000 < port number <= 65536 in android. (less than 10000,
some errors may occur).
If the mobile network is active, the ServerSocket(port number) uses the outgoing IP (mobile network's IP). Try ServerSocket(int port, int backlog, InetAddress localAddress) instead.(You need to specify an address, that is, hotspot's address.)
In ClientActivity.java, I see you pass an IP through execute(ip), but you didn't use it. You can do Socket s = new Socket(ip,5555);.
AsyncTask is not recommended for doing a long time work. Use Thread instead.

turn my TCP android application to jar

I've built a TCP server and now I would like to turn it into a jar so I can use it in many different app. So basically later on I'd like to just include it in other projects. if it was just a list of functions I could figure it out but it's not I'm so I'm not sure. I thought about making it all just one function but it wouldn't run, when I called the function the app would just fail.
Also I hope other people can find this server code useful for their own projects
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
public String serverIP = "127.0.0.1";
private InetAddress serverAddr;
public static final int SERVERPORT = 4444;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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();
}
}
}
}

Categories

Resources