java.net.ConnectException: Connection refused: connect - android

My problem when I try to send a simple "hello world" msg from the pc "client " to the phone "server " and
I tried all possible solution like : starting the server app which is on the phone first then the client but didn't work,
I changed the ip address too but didn't work,
I closed the firewall nothing happened too
Server's code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public class Server{
public void main(String args[]) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(5000);} catch (IOException e) {
e.printStackTrace();
}
while (true) {
// Wait for a client connection.
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
// Create and start a thread to handle the new client
try {
// Get the socket's InputStream, to read bytes
// from the socket
InputStream in = clientSocket.getInputStream();
// wrap the InputStream in a reader so you can
// read a String instead of bytes
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, Charset.forName("UTF-8")));
// Read from the socket and print line by line
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(getApplicationContext(),line,Toast.LENGTH_LONG).show();
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
// This finally block ensures the socket is closed.
// A try-with-resources block cannot be used because
// the socket is passed into a thread, so it isn't
// created and closed in the same block
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}}
Client's code:
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class ClientClass {
public static void main(String args[]) {
try (Socket socket = new Socket("192.168.1.3", 5000);) {
// We'll reach this code once we've connected to the server
// Write a string into the socket, and flush the buffer
OutputStream outStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
writer.println("Hello world!");
writer.flush();
} catch (IOException e) {
// Exception should be handled.
e.printStackTrace();
}
}
}
error:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at ClientClass.main(ClientClass.java:10)
BUILD SUCCESSFUL (total time: 2 seconds)

I was having same error, and i managed to know what causes this error in my case, you have to check two things:
1-Router configuration if you are connected using WiFi because you have to forward your port correctly.(How to Set Up Port Forwarding on a Router, it differs according to router type)
2-If this IP address here is the correct IP address of your mobile or not:
Socket socket = new Socket("192.168.1.3", 5000);
(How To Check Your Android IP Address)

In the MainActivity class, the inner class named Server is never instantiated and the "main" method is neither called too.
Please have a look to this Tutorial post so as to have an example of how to implement a server using sockets with android devices.

Related

Python Serwer and Android Client communication

Hi I creating simple comminication serwer in Python 2.7, my first goal is to send "list" to android App with sockets.
import socket
import sys
HOST = '192.168.0.108' # this is your localhost
PORT = 8888
list=str(["firstitem",'nextitem'])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# socket.socket: must use to create a socket.
# socket.AF_INET: Address Format, Internet = IP Addresses.
# socket.SOCK_STREAM: two-way, connection-based byte streams.
print 'socket created'
# Bind socket to Host and Port
try:
s.bind((HOST, PORT))
except socket.error as err:
print 'Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1]
sys.exit()
print 'Socket Bind Success!'
# listen(): This method sets up and start TCP listener.
s.listen(10)
print 'Socket is now listening'
while 1:
conn, addr = s.accept()
print 'Connect with ' + addr[0] + ':' + str(addr[1])
#receiver
buf = conn.recv(64)
#sender
send=conn.send(list)
print buf
print 'Connect close with ' + addr[0] + ':' + str(addr[1])
s.close()
And I wanna read list from python serwer then i create BufferedReader(new InputStreamReader) to receive data from python but is not going working well.
package com.javacodegeeks.android.androidsocketclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 8888;
private static final String SERVER_IP = "192.168.0.108";
private BufferedReader input;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) throws IOException {
try {
this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
} catch (IOException e)
{
e.printStackTrace();
}
String read = input.readLine();
Log.d("INFO", "onClick: "+read.toString());
}
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();
}
}
}
}
Do you have any ideas why i cant read this list?

using UDP to broadcast on Wifi Direct

i'm new to wifi direct and i want to be able to broadcast a message, because i have a timeline and when i click the Post button i want all the connected devices have that message displayed on their timeline. I am able to send data peer to peer.I have searched about this subject and i found using UDP is a good choice but i don't know how to implement it in wifi direct.
I found this code that uses UDP on wifi to Get the Broadcast Address
InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);}
and this for Sending and Receiving UDP Broadcast Packets
DatagramSocket socket = new DatagramSocket(PORT);
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
could you please help me and explain to me how it works
thanks in advance.
In Android's Wi-Fi P2P there is a concept of "group owner", which is the device that acts as an access point. For the current API the group owner's IP address seems to be set to 192.168.49.1, which I think is hard-coded somewhere. A quick guess on the broadcast address for the group's network will be 192.168.49.255. For all (of a few) devices I have tested so far that turned out to be the case.
One solution is to Multicast a packet to a Multicast Group. All the devices join a Multicast IP and the sender sends the packet to that Multicast IP. Make sure IP you assign falls in the range of Multicast IPs. When dealing with Multicasting, the device needs to acquire a Multicast Lock. Note that since Multicast is based on UDP, some errors in transmissions are expected.
AsyncTask Class for Devices that will receive the packet:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class ReceiverMulticastAsyncTask extends AsyncTask<Void, Integer ,String > {
#Override
protected String doInBackground(Void... params) {
//Acquire the MulticastLock
WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifi.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
//Join a Multicast Group
InetAddress address=null;
MulticastSocket clientSocket=null;
try {
clientSocket = new MulticastSocket(1212);
address = InetAddress.getByName("224.0.0.1");
clientSocket.joinGroup(address);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DatagramPacket packet=null;
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, buf.length);
//Receive packet and get the Data
try {
clientSocket.receive(packet);
byte[] data = packet.getData();
Log.d("DATA", data.toString()+"");
} catch (Exception e) {
e.printStackTrace();
}
multicastLock.release();
try {
clientSocket.leaveGroup(address);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clientSocket.close();
return "";
}
#Override
protected void onPostExecute(String result) {
//do whatever...
}
}
AsyncTask Class for Device that will send the packet:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class SenderMulticastAsyncTask extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void... params) {
int port =1212;
DatagramSocket socket=null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress group = null;
try {
group = InetAddress.getByName("224.0.0.1");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
socket.close();
e.printStackTrace();
}
//Sending to Multicast Group
String message_to_send ="Test";
byte[] buf = message_to_send.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
try {
socket.send(packet);
Log.d("Send", "Sending Packet");
} catch (IOException e) {
// TODO Auto-generated catch block
socket.close();
e.printStackTrace();
}
socket.close();
return "";
}
#Override
protected void onPostExecute(String result) {
//do whatever ...
}
}

Android run code in Service all the time

I want to create a Service that runs in the background and checks if the client sends a message to the server and answers to it.
Here's what I tried so far:
package com.server.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerService extends Service {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
Thread serverThread;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
System.out.println("hello1");
Toast.makeText(this, "Server Started", Toast.LENGTH_LONG).show();
serverThread = new Thread(new Runnable() {
public void run() {
try {
System.out.println("hello2");
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
System.out.println("hello3");
try {
clientSocket = serverSocket.accept();
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
serverThread.start();
}
}
The problem is, that when the code is in onCreate(), it only gets executed when the service gets created, and I want it to run all the time. So where do I have to put the code in the Service class so it runs all the time?
Best Regards,
Alex

android receive and send data through wifi connection to hardware

Actually I want to send data from a hardware piece to an android device.
The hardware device is connected to local wireless router which is connected to modem.
Android device will also connected to same router through WI-FI.
Can you please suggest some links or tutorial from where i can get idea how to establish communication between hardware device an the android device to send and receive data through WI-FI .Please Help any sample code or links
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
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.TextView;
public class SimpleClientActivity extends Activity {
private Socket client;
private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private Button button;
private TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button1); //reference to the send button
text = (TextView) findViewById(R.id.textView1); //reference to the text view
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
File file = new File("/mnt/sdcard/input.jpg"); //create file instance, file to transfer or any data
try {
client = new Socket("10.0.2.2", 4444);// ip address and port number of ur hardware device
byte[] mybytearray = new byte[(int) file.length()]; //create a byte array to file
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedInputStream.read(mybytearray, 0, mybytearray.length); //read the file
outputStream = client.getOutputStream();
outputStream.write(mybytearray, 0, mybytearray.length); //write file to the output stream byte by byte
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
text.setText("File Sent");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
// to send message u can also use below code
public static String ipAddress;// ur ip
public static int portNumber;// portnumber
private Socket client;
private OutputStreamWriter printwriter;
private String message;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
client = new Socket(ipAddress, portNumber);
printwriter = new OutputStreamWriter(client
.getOutputStream(), "ISO-8859-1");
printwriter.write("any message");
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();

Connecting two phones using socket

Is it possible to connect two phones using socket programming?
I tried following code but it didn't work
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();//Public function to get ip address to it is //working fine
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(8087);
} else {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
As per socket programming two client socket cannot connect each other. similarly two server socket cannot connect eachother. The code you have written tells that you have written server socket. u need a client socket which will connect to server socket. to create client socket u need ip and port of server socket. Please have a look on the code below. Donot forget to vote if you find the response is useful for you. The below example is in core java. u can implemnet the both in andriod also.
Server
-------
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Client
--------------
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Thanks
Deepak
Yes, it is possible but I think the first thing you should do is read up on Java Socket programming as there are a few problems with your code that make me think you haven't quite got a grasp of it yet. The main problems are:
Your ServerSocket never accepts a connection and is therefore never actually 'listening'.
Even if it was listening, if this code is running on both phones they would both only be listening and not actively seeking a connection with each-other.
You will need to implement a client on one phone and a server on the other like #Deepak has shown.
Also, you may want to check out AsyncTask in this article for updating views from a non-UI thread (instead of a handler).
Finally, make sure your app includes the android.permission.INTERNET permission in AndroidManifest.xml.

Categories

Resources