Impossible connecting to printer in thread - android

My problem is the next: I'm trying to print with my printer via wifi, I can print if I print a unique line. What I need is to create a kind of printer server which is listening requests to print all time in a loop, and through an arraylist with products what I want to print line by line. This is the code that I'm using:
for(FinalBarto barto : bartoProducts){
Product product = barto.getProducts();
MyPrinter printer = new MyPrinter(product,cxt);
printer.start();
}
And this is the class MyPrinter:
public class MyPrinter extends Thread {
Product producto;
Pack pack;
Context context;
Socket socket;
PrintWriter printWriter;
public MyPrinter(Product producto, Context context){
this.context = context;
this.producto = producto;
}
#Override
public void run() {
try {
socket = new Socket("192.168.0.254",9100);
printWriter = new PrintWriter(socket.getOutputStream());
printWriter.println("HELLO FROM THE THREAD");
} catch (IOException e) {
e.printStackTrace();
}
}
}
As you can see I am setting the IP and the port right there, and I've sent a ping to my printer and this is the correct IP and port. So, I don't know where the problem is, I can't see it.
The error that I obtaing from Android Studio is:
java.net.ConnectException: failed to connect to /192.168.0.254 (port 9100): connect failed: ECONNREFUSED (Connection refused)
Thank you in fordward!

Related

What will be the correct IP address if I want to establish socket connection between pc and Android emulator?

I am trying to use pc as server and Android emulator as client.I want to send a message from server to client.Here's the code:
server:
import java.net.*;
import java.io.*;
public class SimpleServer {
public static void main(String[] args)
throws IOException
{
ServerSocket ss = new ServerSocket(30000);
while(true) {
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
os.write("Hello World!\n".getBytes("utf-8"));
os.close();
s.close();
}
}
}
Client:
public class MainActivity extends AppCompatActivity {
EditText text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText)findViewById(R.id.messg);
new Thread() {
#Override
public void run() {
try {
// What ip address should be chosen here?
Socket socket = new Socket("xxx.xxx.xxx.xxx",30000);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = br.readLine();
text.setText(line);
br.close();
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
I have test the code of server and client on the same computer using localhost:127.0.0.1 and it works.However, I can't figure out if the client is the emulator launched by genymotion on the same computer, what will be the correct IP address for the client socket to connect?
I am using wifi and I have tried IP address of wlan0 (found by ifconfig),127.0.0.1, and the public IP address of my computer (found by Google), but the client emulator doesn't display the message from server.
If you want to refer to the computer which is running the Android simulator, use the IP address 10.0.2.2 instead. You can read more about it here
Have you tried the local area network IP address of the computer? In your ifconfig you must get something line
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
...
inet 192.168.43.238
So use 192.168.43.238

Android client to java server

I want to create an application on android that checks if user is in the server database. At this moment, i just try to make connection work.
This is my client code :
public class Client {
public void testConnexion() {
new LoadTesting().execute();
}
class LoadTesting extends AsyncTask<String, String, String> {
private final String HOST_ADDRESS = "23.248.21.91";
private final Integer HOST_PORT = 2009;
#Override
protected String doInBackground(String... params) {
Socket socket;
try {
Log.d("CASERVER", "Connexion...");
InetAddress srvAddress = InetAddress.getByName(HOST_ADDRESS);
socket = new Socket(srvAddress, HOST_PORT);
Log.d("CASERVER", "Connexion successful !");
// DO SOMETHING
socket.close();
} catch (IOException e) {
e.printStackTrace();
Log.w("CASERVER", e.getMessage(), e);
}
return null;
}
}
}
And the server part
public class Server {
public static final int HOST_PORT = 2009;
public static void main(String[] args) {
ServerSocket serverSocket;
Socket socketDuServeur;
try {
serverSocket = new ServerSocket(HOST_PORT);
socketDuServeur = serverSocket.accept();
// DO SOMETHING
serverSocket.close();
socketDuServeur.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have add those permission
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
My server is on my macbook connected to my wifi.
I've got two Eclipse Window : one for android and one for the server.
The test :
1 Launch the server, the server is waiting for connection
2 Launch the application on the mobile device and try to connect the server
I expect the result :
Connexion...
Connexion successful ! (Or an error)
I've got the following Log result instead :
Connexion...
No error, no successful. Just nothing...
When i shut down manually the server (with another client on laptop) i've got EHOSTUNREACH error (device can't found the server)
Can you help me ?

Android socket connection refused error

I want to implement socket connection between 2 deceives , client keep sending GPS data to the server and I need both of it run in new thread , the client send first one data then keep show error like this
03-18 16:35:11.805: E/Client run:(8163): java.net.ConnectException: failed to connect to /192.168.2.103 (port 5678): connect failed: ECONNREFUSED (Connection refused)
here is the client code
public class Send implements Runnable{
private boolean Connect = true;
public void Connect(){
Connect = true;
}
public void Disconnect(){
Connect = false;
}
#Override
public void run() {
// TODO Auto-generated method stub
while(Connect){
try {
SocketClient = new Socket("192.168.2.103", 5678);
ObjectOutputStream oos = new ObjectOutputStream(SocketClient.getOutputStream());
oos.writeDouble(GPSinfo[2]);
//ObjectInputStream ois = new ObjectInputStream(SocketClient.getInputStream());
//ois.readInt();
oos.close();
//ois.close();
} catch (Exception e) {
Log.e("Client run: ", e.toString());
}
}
}
}
here is server code
public class Receive implements Runnable{
private boolean CanReceive = true;
private double Data;
public void Connect(){
CanReceive = true;
}
public void Disconnect(){
CanReceive = false;
}
#Override
public void run() {
// TODO Auto-generated method stub
while(CanReceive){
try {
SocketServer = new ServerSocket(5678);
Socket connectedSocket = SocketServer.accept();
ObjectInputStream ois = new ObjectInputStream(connectedSocket.getInputStream());
Data = ois.readDouble();
DataText.setText("" + Data);
//ObjectOutputStream oos = new ObjectOutputStream(connectedSocket.getOutputStream());
//oos.writeInt(1);
//ois.close();
//oos.close();
} catch (Exception e) {
Log.e("Server run: ", e.toString());
}
}
}
}
by the way , the both code is inner class , and INTERNET permission is added.
It's obvious it's not a router-firewall related problem as you are under the same net, so there are only a few possibilities:
There's nothing listening on that port on that IP on the server-side
There's a local firewall on the server-side that is blocking that connection attempt
You are not using WIFI so you're not under the same net.
You should make sure you can open that service some ther way, that would help you debugging where the culprit is. If you've already done this, I'd suggest using some debugging tool to trace TCP packets (I don't know either what kind of operating system you use on the destination machine; if it's some linux distribution, tcpdump might help, in Win environments WireShark works just good).
This isn't a 'data transfer error'. This is a 'connection refused' error. It means the server you want to transfer the data to or from isn't running at the IP:port you specified.
Try killing the adb service before you begin the connection. I had a similar problem and killing the adb service before the connection resolved the issue.
I had the same error. I simply used ServerSocket and it worked well.
ServerSocket socket = new ServerSocket(8888);

Broadcasting with WiFi Direct in android

I am beginner in android programming. Am trying to broadcast messages on WiFiDirect using the following code:
public class FileTransferService extends IntentService {
public static final String host= "255.255.255.255";
InetAddress broadcastAddress = InetAddress.getByName(host);// Exception: Unknown host exception
int port = 8888;
protected void onHandleIntent(Intent intent) {
Log.d(WiFiDirectActivity.TAG,"m in 1");
Context context = getApplicationContext();
DatagramSocket socket;
try {
socket = new DatagramSocket(port);
socket.setBroadcast(true);
socket.connect(broadcastAddress, port);
String message = "Hello";
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, broadcastAddress, port);
socket.send(packet); // <----- Causes a SocketException
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.getMessage(), e);
}
}
}
It shows me unknown host exception on getByName() method. Is there anyway to replace the method? Am I going on a right path? Do I need to add anything along with this to send messages.
Thanks in advance
Try calling public UnknownHostException (String detailMessage) to get the detailed exception message.
Another way to call getByName() can be get from here
Below link has a step by step illustration of setting up a Wi-Fi Direct broadcaster
Connecting with Wi-Fi Direct

WIFI to WIFI Connectivity using Android

I want to transfer messages from the android device to desktop application. My question is that can i connect the android WiFi device with the desktop WiFi device without any use of internet connection. I want to use it just like the Bluetooth. is this possible or not? if it is possible then how can i implement it?
Thanks and Regards
Amit Thaper
Here is an implementation of mreichelt's suggestion. i looked this up when i had the same problem and figured i'd just post my implementation of the solution. it's really simple. i also built a java server that listens for incoming requests from the android device (for debugging purposes mostly). here's the code to send stuff over the wireless:
import java.net.*;
import java.io.*;
import java.util.*;
import android.app.Activity;
import android.content.Context;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
public class SMSConnection {
/* The socket to the server */
private Socket connection;
/* Streams for reading and writing the socket */
private BufferedReader fromServer;
private DataOutputStream toServer;
/* application context */
Context mCtx;
private static final String CRLF = "\r\n";
/* Create an SMSConnection object. Create the socket and the
associated streams. Initialize SMS connection. */
public SMSConnection(Context ctx) throws IOException {
mCtx=ctx;
this.open();
/* may anticipate problems with readers being initialized before connection is opened? */
fromServer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
toServer = new DataOutputStream(connection.getOutputStream());
}
public boolean open(String host, int port) {
try {
connection = new Socket(host, port);
return true;
} catch(IOException e) {
Log.v("smswifi", "cannot open connection: " + e.toString());
}
return false;
}
/* Close the connection. */
public void close() {
try {
connection.close();
} catch (IOException e) {
Log.v("smswifi","Unable to close connection: " + e.toString());
}
}
/* Send an SMS command to the server. Check that the reply code
is what is is supposed to be according to RFC 821. */
public void sendCommand(String command) throws IOException {
/* Write command to server. */
this.toServer.writeBytes(command+this.CRLF);
/* read reply */
String reply = this.fromServer.readLine();
}
}
that's a basic skeleton for a connection class. you simply instantiate the class, and call open on the instance you create with the host and port (don't forget to close the connection when you're done) and you can change the body of sendCommand to your liking. i've included a read/write operation in the function body as an example.
here is the code to run a server on a remote machine that listens for connections and spawns a thread to handle each request. it can easily interact with the above code for debugging (or any use).
import java.io.*;
import java.net.*;
import java.util.*;
public final class smsd {
///////MEMBER VARIABLES
ServerSocket server=null;
Socket client=null;
///////MEMBER FUNCTIONS
public boolean createSocket(int port) {
try{
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port "+port);
System.exit(-1);
}
return true;
}
public boolean listenSocket(){
try{
client = server.accept();
} catch (IOException e) {
System.out.println("Accept failed: ");
System.exit(-1);
}
return true;
}
public static void main(String argv[]) throws Exception {
//
smsd mySock=new smsd();
//establish the listen socket
mySock.createSocket(3005);
while(true) {
if(mySock.listenSocket()) {
//make new thread
// Construct an object to process the SMS request message.
SMSRequest request = new SMSRequest(mySock.client);
// Create a new thread to process the request.
Thread thread = new Thread(request);
// Start the thread.
thread.start();
}
}
//process SMS service requests in an infinite loop
}
///////////end class smsd/////////
}
final class SMSRequest implements Runnable {
//
final static String CRLF = "\r\n";
Socket socket;
// Constructor
public SMSRequest(Socket socket) throws Exception
{
this.socket = socket;
}
// Implement the run() method of the Runnable interface.
public void run()
{
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception
{
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 ) {
os.write(buffer, 0, bytes);
}
}
private void processRequest() throws Exception
{
// Get a reference to the socket's input and output streams.
InputStream is = this.socket.getInputStream();
DataOutputStream os = new DataOutputStream(this.socket.getOutputStream());
// Set up input stream filters.
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// Get the request line of the SMS request message.
String requestLine = br.readLine();
//print message to screen
System.out.println(requestLine);
//send a reply
os.writeBytes("200");
// Close streams and socket.
os.close();
br.close();
socket.close();
}
}
nb4namingconventions.
almost forgot. you will need to set these permissions inside the tags in your AndroidManifest.xml in order to use wireless.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
This is easily possible if both devices are using the same wifi network and can ping each other. You may just create a Java application on your desktop which creates a ServerSocket. Then you can open a Socket in your Android app using the desktop's IP address and send data through the OutputStream.
I believe that Amit is referring to having the machines connect directly to each other using wireless.
There is the development currently of the Wifi-direct specification to allow for Plug-in-Play setup of Access Points. The issue currently is ensuring one of the machines is an AP that other machine(s) can establish connection to.
I'm interested in how this relates to Ad-Hoc networks. I don't have a solution, however I am quite interested in this question too ! (Assuming this is your question Amit).

Categories

Resources