I am trying to etablish a connection to a monero mining pool. I know that the mining pools using the stratum protocol. But the only thing I receive is a connection timeout if I try to create a socket:
try{
InetAddress address = InetAddress.getByName("pool.supportxmr.com");
Log.d("miner","Attempting to connect to " + address.toString() + " on port " + port + ".");
Socket socket = new Socket(address, 3333);
Log.d("miner", "Connection success");
}catch (IOException e){
e.printStackTrace();
}
SupportXmr is just an example. Its not working with any pool. What am I doing wrong?
Try with port 80. Make sure you wrote INTERNET permission to AndroidManifest and use AsnycTask.
private class AsyncExec extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
int port=80;
try
{
InetAddress address = InetAddress.getByName("pool.supportxmr.com");
Log.d("miner","Attempting to connect to " + address.toString() + " on port " + port + ".");
Socket socket = new Socket(address, 3333);
Log.d("miner", "Connection success");
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
- Also don't forget to call new AsyncExec().execute().
Related
Below code hangs does not go past beyond below messages and is hanging at socket.accept().
Its part of an android app and INTERNET permissions are already added to manifest. Tried putting accept in while(true) loop...but that did not work:
09-23 15:55:43.737 24079-25436: Trying to open port 5556...
09-23 15:55:43.739 24079-25436: >>> Opening Port : 5556
private Socket socket = null;
private ServerSocket server = null;
private static final String TAG = "MyActivity";
public boolean openPort(String host , int port){
try {
server = new ServerSocket(port);
} catch (IOException e) {
Log.e(TAG , "Error initializing serverSocket: " , e);
}
Log.e(TAG , ">>> Opening Port : " + port);
boolean bmsg = false;
try {
socket = server.accept();
Log.e(TAG , ">>> Opened Port : " + port);
return true;
} catch(IOException e){
Log.e(TAG, "Error opening port: ", e);
return bmsg;
} catch(SecurityException s){
Log.e(TAG, "sError opening port: ", s);
return bmsg;
} catch(IllegalBlockingModeException b){
Log.e(TAG, "bError opening port: ", b);
return bmsg;
}
}
Above class is being called from below async task on button click:
private class openPort extends AsyncTask{
#Override
protected Object doInBackground(Object[] objects) {
Log.i(TAG , "Trying to open port 5556...");
//host is localhost
//port is 5556
OpenClosePort ocp = new OpenClosePort();
ocp.openPort(host , port);
return null;
}
}
I am trying to get into IoT and want to make an app send a string from an android phone to a Linux pc. The app does this by implementing an asynctask:
//From the java docs, slightly modified
private Void sendThroughSocket(String s, String host, int port) {
Log.d("E", "In send through socket");
final String hostName = host;//Host is the address of the receiver, can be IP or domain
int portNumber = port;
//Check if device is connected to internet
try {
Socket clientsocket = new Socket(hostName, portNumber); //one of 2-way point communication
Log.d("E", "Created Socket: ");
DataOutputStream DOS = new DataOutputStream(clientsocket.getOutputStream());
if (clientsocket.isConnected())
Log.d("E", "Socket connected");
DOS.writeUTF(s);
clientsocket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
new Runnable() {
public void run() {
Toast.makeText(context, "Don't know about host " + hostName, Toast.LENGTH_SHORT).show();
}
};
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + hostName);
//Toast can not be run using asynctask since it acesses UI
new Runnable() {
public void run() {
Toast.makeText(context, "Couldn't get I/O for the connection to " + hostName + " , check the port", Toast.LENGTH_SHORT).show();
}
};
} catch (Exception e) {
Log.d("E", "#fares" + e.getClass().getName().toString());
}
return null;
}
On 3 occasions do I try to send the string, all triggered from my seekbar (I send the seek bar progress value as my string):
public void onProgressChanged(SeekBar seekBar, int i, boolean b)
public void onStartTrackingTouch(SeekBar seekBar)
public void onStopTrackingTouch(SeekBar seekBar)
The implementation for all 3 is the same:
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
progressvalue = i;
textView.setText("Brightness = " + progressvalue + " %");
if (((RecieverPort.equals("Please enter port Number")) || (RecieverIP.equals("Please enter receiver IP")))) {
//Make sure toast isn't persistent
if (IPPortToastcount++ == 0)
Toast.makeText(MainActivity.this, "Please set both IP and Port ", Toast.LENGTH_SHORT).show();
} else {
//Check if connected to internet
if (!isConnectedtoInternet(MainActivity.this)) {
if (ConnectivityToastCount++ < 1)
Toast.makeText(MainActivity.this, "You are not connected to the Internet", Toast.LENGTH_SHORT).show();
} else {
//Send text over wifi
SendText ST = new SendText(getApplicationContext());
ST.execute(String.valueOf(progressvalue), RecieverIP, RecieverPort);
ST.cancel(false);
}
}
}
Mainly
//Send text over wifi
SendText ST = new SendText(getApplicationContext());
ST.execute(String.valueOf(progressvalue), RecieverIP, RecieverPort);
ST.cancel(false);
The server side (my pc) is pretty simple:
int portNumber = 44339; // Choose unused port on router
//Open a socket
try {
//System.out.println("in try statement");
try (ServerSocket serverSocket1 = new ServerSocket(portNumber)) {
portNumber = serverSocket1.getLocalPort();
System.out.println("Created socket at port " + portNumber);
Socket clientSocket = serverSocket1.accept();
System.out.println("Accepted");
DataInputStream DIS = new DataInputStream(clientSocket.getInputStream()); //get input from socket
//System.out.println("Created reader");
String inputLine;
// System.out.println("About to read");
while (DIS.available() > 0) {
inputLine = DIS.readUTF();
System.out.println(inputLine);
}
}
} catch (Exception e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getClass().getSimpleName());
}
This kind of works, except it takes a very long time(seconds) before the server socket is accepted. It also only works in onprogresschanged , which leads me to believe that multiple attempts of
//Send text over wifi
SendText ST = new SendText(getApplicationContext());
ST.execute(String.valueOf(progressvalue), RecieverIP, RecieverPort);
ST.cancel(false);
are needed before one succeeds at creating the socket and connecting to the pc. How can I make sure that one tap, or one call of the function will be enough to send the string?
Sorry for the long post but it's my first time asking :)
Edit: my new server code:
try {
//System.out.println("in try statement");
try ( ServerSocket serverSocket1 = new ServerSocket(portNumber))
{
portNumber = serverSocket1.getLocalPort();
System.out.println("Created socket at port " + portNumber);
while(true){
Socket clientSocket = serverSocket1.accept();
// System.out.println("Accepted");
DataInputStream DIS = new DataInputStream(clientSocket.getInputStream()); //get input from socket
//System.out.println("Created reader");
//String inputLine;
//System.out.println("About to read");
System.out.println(DIS.readUTF());
}
}
} catch (Exception e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getClass().getSimpleName());
}
Worth noting that even in the while true loop, the server will always display 4 numbers then stop.
Edit: here is an example log:
10-06 20:08:09.145 26372-26372/com.example.fares.ledslider D/E: #fares in test method value = 50
10-06 20:08:26.475 26372-26372/com.example.fares.ledslider D/E: #Fares in start tracking
10-06 20:08:26.722 26372-27004/com.example.fares.ledslider D/E: #fares Socket connected
10-06 20:08:26.810 26372-26764/com.example.fares.ledslider D/E: #fares Socket connected
10-06 20:08:27.241 26372-27003/com.example.fares.ledslider D/E: #fares Socket connected
10-06 20:08:27.304 26372-26372/com.example.fares.ledslider D/E: #fares in stop tracking
ST.cancel() can be removed. Also not waiting for availability looks not good.
I am trying to make connection between multiple device one act as server or group owner and other as client, which I have implemented using wifi direct and wifi p2p and working fine.
After device connected in a group, i am trying to make socket connection between the server and multiple clients but I can't connect using socket. showing below error
java.net.ConnectException: failed to connect to /192.168.49.1 (port 8988) after 5000ms: isConnected failed: ECONNREFUSED (Connection refused)
SockertServer code
#Override
protected Object doInBackground(Object[] params) {
try {
server = new ServerSocket(8988);
Log.d("ServerActivity", "Server: Socket opened");
Log.d("ServerActivity", server.getLocalPort() + "");
Log.d("ServerActivity", server.getInetAddress() + "");
Socket client = server.accept();
Log.d("ServerActivity", "Server: connection done");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
client.getOutputStream()
);
objectOutputStream.writeObject("Hie");
client.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Client Socket
#Override
protected Object doInBackground(Object[] params) {
try {
mSocket = new Socket();
mSocket.bind(null);
mSocket.connect((new InetSocketAddress(getAddr, portNo)), SOCKET_TIMEOUT);
if (mSocket.isConnected()) {
Log.d("Client Activity", "Socket Connected Successfully");
} else {
Log.d("Client Activity", "Socket not Connected ");
}
ObjectInputStream objectOutputStream = new
ObjectInputStream(mSocket.getInputStream());
msg = (String) objectOutputStream.readObject();
message.onMessageSend(msg);
Log.e(".......................", "Message" + msg);
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (mSocket != null) {
if (mSocket.isConnected()) {
try {
mSocket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
return msg;
}
So anyone can help me out with this problem.Thanks in advance!!
ECONNREFUSED means that the connection was attempted and the remote host port is not listening. Hence this can be caused because of:
Is it a valid IP? check using ifconfig or ipconfig. you can try pinging the server.
It may also be due to the following reasons:
-The server couldn't send a response: Ensure that the backend is working properly at IP and port mentioned.
-SSL connections are being blocked.
-Request timeout: Change request timeout
I'm trying to write simple server-client chat solution. For test purposes, I'm creating an array of 2 serverThreads, which are responsible for sending and receiving messages from the clients connected.
I'd like a server to reject a connections after the number of connected clients reach a maximum value. However, even though the server do not accept the connection, the socket on client side is created. Methods socket.isBound and isConnected both return true value.
So back to the main question. Do you have any ideas how could I reject the client from connecting when the ServerSocket will not be able to .accept() additional connection?
Here's the code of the Server class.
public class Server {
private ServerSocket serverSocket = null;
private ServerThread serverThread[] = new ServerThread[2];
protected volatile int clientCount = 0;
public Server (int port){
try {
System.out.println("Binding to port " + port + " ...");
serverSocket = new ServerSocket (port);
System.out.println("Binded to port " + port + ".");
} catch (IOException e) {
System.out.println("Failed binding to the port: " + e.getMessage());
}
}
public void addThread (Socket socket){
System.out.println ("Client connected at socket: " + socket);
serverThread[clientCount] = new ServerThread (this, socket);
try {
serverThread[clientCount].open();
serverThread[clientCount].start();
} catch (IOException e) {e.getMessage();}
}
public void waitForClient () {
boolean isLogPrinted = false;
while (true){
try {
if (clientCount < serverThread.length){
System.out.println ("Waiting for connection...");
isLogPrinted = false;
addThread (serverSocket.accept());
clientCount++;
System.out.println("Client count: " + clientCount);
}
else {
if (!isLogPrinted){
System.out.println("MAXIMUM NUMBER OF CLIENTS REACHED! (" + clientCount + ").");
isLogPrinted = true;
}
}
} catch (IOException e) {
System.out.println("Error while waiting for new clients to connect: " + e.getMessage());
}
}
}
public synchronized void broadcastMessages (String msg){
for (int i = 0; i < clientCount; i++)
serverThread[i].sendMessage(msg);
}
public static void main (String args[]){
Server server = new Server (4200);
server.waitForClient();
}
}
I'd like a server to reject a connections after the number of connected clients reach a maximum value.
Close the server socket.
However, even though the server do not accept the connection, the socket on client side is created. Methods socket.isBound and isConnected both return true value.
Correct. That's because TCP maintains a 'backlog queue' of incoming connections which have been completed but not yet accepted by the server application.
So back to the main question. Do you have any ideas how could I reject the client from connecting when the ServerSocket will not be able to .accept() additional connection?
Close the server socket while the number of connections is at its maximum.
However due to the backlog this technique can never be perfect. There is no perfect solution. You could have the server immediately close excess connections, but the excess clients won't detect that until they try to send something. If you need perfection you will probably have to introduce an application protocol whereby the server sends something like 'ACCEPTED' or 'REJECTED' accordingly.
Instead of while true in you waitForClient method try this
private final int allowedClients = 10;
private int connectedClients = 0;
public void waitForClient () {
boolean isLogPrinted = false;
while (connectedClients <= allowedClients){
try {
if (clientCount < serverThread.length){
System.out.println ("Waiting for connection...");
isLogPrinted = false;
addThread (serverSocket.accept());
connectedClients++;
System.out.println("Client count: " + clientCount);
}
else {
if (!isLogPrinted){
System.out.println("MAXIMUM NUMBER OF CLIENTS REACHED! (" + clientCount + ").");
isLogPrinted = true;
}
}
} catch (IOException e) {
System.out.println("Error while waiting for new clients to connect: " + e.getMessage());
}
}
}
I know this is very late to answer, but I think it will help many.
You can check for the existing socket if any by below code.
SocketAddress socketAddress = new InetSocketAddress("localhost", 8091);
Socket socket = new Socket();
ServerSocket serverSocket = null;
try {
socket.connect(socketAddress);
} catch (IOException e) {
e.printStackTrace();
}
if(socket == null) {
try {
serverSocket = new ServerSocket(8091);
} catch (IOException e) {
e.printStackTrace();
}
}
if not found a active socket on the same port and IP then it will start a new server socket or you can change it start socket only else you can connect to the existing socket.
i want to connect morethan one client at a time to the server and also communicate server to all the clients.
how server recognize each client. and how to send data to a particular client?
consider , there are 3 clients A,B,C. all the clients are connected to the server. the server wants to send message to B. how its done ?
If i understand you right - all you need is not bind socket for one connection.
Your client code will looks like that:
Client class:
public class TCPClient {
public TCPClient(String host, int port) {
try {
clientSocket = new Socket(host, port);
} catch (IOException e) {
System.out.println(" Could not connect on port: " + port + " to " + host);
}
}
Server(host) class:
public class TCPListener {
public TCPListener(int portNumber) {
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println("Could not listen on port: " + portNumber);
}
System.out.println("TCPListener created!");
System.out.println("Connection accepted");
try {
while (true) {
Socket clientConnection = serverSocket.accept();
//every time client's class constructor called - line above will be executed and new connection saved into Socket class.
}
} catch (Exception e) {
e.printStackTrace();
}
}
That is simplest example. More can be found here:
http://www.oracle.com/technetwork/java/socket-140484.html