logo
down
shadow

Which is better between an android app and a server? Socket or timer?


Which is better between an android app and a server? Socket or timer?

By : Michael
Date : November 19 2020, 03:59 PM
This might help you It really depends on what you want to do, but here are some answers :
Reopening a TCP connection every few seconds probably won't hurt. Close+reopen is how most HTTP connections work. An idle TCP socket doesn't send any traffic at all, unless you enable TCP keepalive, but even then it is still very light (and often adjustable). Usually a lot, but is really depends on your software and hardware. A desktop computer may have 1000 open connections on normal load (but can certainly handle more). A big server may handle millions open connections.
code :


Share : facebook icon twitter icon
Starting Timer problem from Asynchronous Server Socket

Starting Timer problem from Asynchronous Server Socket


By : user3339679
Date : March 29 2020, 07:55 AM
hope this fix your issue If the timer is a Windows.Forms.Timer, you'll need to call Control.Invoke to marshal the call that sets the timer properties and starts the timer back on the UI thread.
You should also do this for all of your text box and other UI elements. I suspect this is your problem, since socket communication typically occurs on a ThreadPool thread and not on the main (UI) thread.
How to stop server-side timer on user disconnect? (node.js/socket.io)

How to stop server-side timer on user disconnect? (node.js/socket.io)


By : SteemeX
Date : March 29 2020, 07:55 AM
With these it helps I have some server-side timer, that worked on socket.io: , You can use a function to store the context of serverInterval like
code :
var ServerInterval = (function () {
    var serverInterval;
    return {
            set: function (obj) {
            serverInterval = obj;
            },
            get : function() {
                return serverInterval;
            }
    };

})();

// timer function
    function startTimer() {
         var countdown = 15000;
         ServerInterval.set(setInterval(function () {
            countdown -= 1000;
            socket.in(room_name).emit('timer', {countdown: countdown});
         }, 1000));
     }

// timer usage      
     socket.on("start timer", function() {
         startTimer()
     }

socket.on('disconnect', function() {
      clearInterval(ServerInterval.get());
});
How to stop timer on server, when user disconnect? (Node.js/socket.io)

How to stop timer on server, when user disconnect? (Node.js/socket.io)


By : Thodoris Tsatsoulis
Date : March 29 2020, 07:55 AM
this will help On the server there is a timer, when it starts, the countdown starts, but when the user leaves the page, the timer continues to run and is triggered when the user is no longer on the page. How can I stop this timer before the user leaves the page or when it already leave? , You need to store timerID and use the same in clearTimeout
code :
var socketTimer;
    function startTimer() {
            console.log("Timer statrted!");
            var countdown = 15000;
            socketTimer = setTimeout(function () {
                console.log("Timer done!");
            }, 15000);
        }

    function stopTimer (){
        clearTimeout(socketTimer);
    }
        socket.on("get data", function() {
             io.to(room_name).emit("data");
             //call timer
             startTimer(); //"Timer started!", "user disconnected", (after 15s) "Timer done!"
         });



         socket.on("disconnect" ,function(){
             console.log("user disconnected");   
             stopTimer();
         });
Can i connect an android client through native java.net.Socket with a node js server which uses socket.io?

Can i connect an android client through native java.net.Socket with a node js server which uses socket.io?


By : Ahmet Salih Şimşek
Date : March 29 2020, 07:55 AM
To fix the issue you can do Here I found a solution that works fine. This code section is for server side socket.
code :
var net = require('net');
var sockets = [];

var svr = net.createServer(function(sock) {
    console.log('Connected: ' + sock.remoteAddress + ':' + sock.remotePort);
    sockets.push(sock);

    sock.write('Welcome to the server!\n');

    sock.on('data', function(data) {
        for (var i=0; i<sockets.length ; i++) {
            if (sockets[i] != sock) {
                if (sockets[i]) {
                    sockets[i].write(data);
                }
            }
        }
    });

    sock.on('end', function() {
        console.log('Disconnected: ' + sock.remoteAddress + ':' + sock.remotePort);
        var idx = sockets.indexOf(sock);
        if (idx != -1) {
            delete sockets[idx];
        }
    });
});

var svraddr = '192.168.0.8';
var svrport = 1234;

svr.listen(svrport, svraddr);
console.log('Server Created at ' + svraddr + ':' + svrport + '\n');
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class Client {
private Socket socket;
private OutputStream socketOutput;
private BufferedReader socketInput;

private String ip;
private int port;
private ClientCallback listener=null;

public Client(String ip, int port){
    this.ip=ip;
    this.port=port;
}

public void connect(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            socket = new Socket();
            InetSocketAddress socketAddress = new InetSocketAddress(ip, port);
            try {
                socket.connect(socketAddress);
                socketOutput = socket.getOutputStream();
                socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                new ReceiveThread().start();

                if(listener!=null)
                    listener.onConnect(socket);
            } catch (IOException e) {
                if(listener!=null)
                    listener.onConnectError(socket, e.getMessage());
            }
        }
    }).start();
}

public void disconnect(){
    try {
        socket.close();
    } catch (IOException e) {
        if(listener!=null)
            listener.onDisconnect(socket, e.getMessage());
    }
}

public void send(String message){
    try {
        socketOutput.write(message.getBytes());
    } catch (IOException e) {
        if(listener!=null)
            listener.onDisconnect(socket, e.getMessage());
    }
}

private class ReceiveThread extends Thread implements Runnable{
    public void run(){
        String message;
        try {
            while((message = socketInput.readLine()) != null) {   // each line must end with a \n to be received
                if(listener!=null)
                    listener.onMessage(message);
            }
        } catch (IOException e) {
            if(listener!=null)
                listener.onDisconnect(socket, e.getMessage());
        }
    }
}

public void setClientCallback(ClientCallback listener){
    this.listener=listener;
}

public void removeClientCallback(){
    this.listener=null;
}

public interface ClientCallback {
    void onMessage(String message);
    void onConnect(Socket socket);
    void onDisconnect(Socket socket, String message);
    void onConnectError(Socket socket, String message);
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Client socket = new Client("192.168.0.8", 1234);
    socket.setClientCallback(new Client.ClientCallback () {
        @Override
        public void onMessage(String message) {
        }

        @Override
        public void onConnect(Socket socket) {
                socket.send("Hello World!\n");
                socket.disconnect();
        }

        @Override
        public void onDisconnect(Socket socket, String message) {
        }

        @Override
        public void onConnectError(Socket socket, String message) {
        }
    });

    socket.connect();
}
}
Android connects to java server socket, but server socket is not receiving data

Android connects to java server socket, but server socket is not receiving data


By : Walter
Date : March 29 2020, 07:55 AM
hope this fix your issue Couldn't stop thinking about this, because it seems so strange. I have an explanation, though, so I will take a stab at the answer:
You have two client connections reaching the server. Connection 1 connects and doesn't send anything (reason unknown). Connection 2 connects and sends the data payload. The server never even attempts to read that payload, however, because it's stuck dutifully waiting for connection 1 to send something (which it never does). The second socket is never even accept()-ed.
Related Posts Related Posts :
  • Facebook login with Parse always returns false in user.isNew() Android
  • I get NullPointerException in an Android animation?
  • Things move out of place on different screen sizes
  • android database: the method open() is undefined for the type databasehelper class
  • sending intent with a parcelable extra from widget crashes on activity startup
  • How to record a video less than 10 mb using Android
  • Android - serialize object to pass it over Bluetooth NotSerializableException
  • Facebook Login Button Android in Eclipse
  • Null pointer exception on adding a marker to google maps
  • Jackson : Can not deserialize instance of java.util.ArrayList out of VALUE_TRUE token
  • How to customize PagerTitleStrip android
  • Click event not being captured for ListView items with HorizontalScrollView
  • HAX kernel module is not installed
  • Android: signed watchface on Android Wear 5.0 not installed
  • Dialog Builder in PreferenceFragment
  • HttpClient change UserAgent
  • Numerous 'No resource found' and 'Error retrieving parent' in Android Project
  • Get call log of a particular number
  • Invalid "--android-sdk" value "C:\android-sdk-win" in Titanium while deploying app on android mobile
  • Call onResume() method from Asynctask's onPostExecute() Method
  • Linking with native SO file present in included library project of Android
  • GridView error in horizontal spacing
  • Progressbar on bottom of listview item
  • Adding Markers on Google maps v2 Android
  • How to Remove Duplicate Libraries added via gradle?
  • Datepicker Dialog Validation...!
  • Scale image in ImageView to width of the parent and scale in height accordingly
  • user level api 19 failed to load. What files should i download
  • While running android AVD manager it shows error "HAX kernel module is not installed!"
  • Android application for limited enterprise audience
  • How to align different elements vertically in android studio?
  • Scroll View is not working when keyboard is open
  • Android phone Lg Realm(ls620) no driver found and can't find one online
  • Pros and cons for using external libraries in android project
  • What is the path of OAT file in Android 5.0
  • Actionbar Sherlock How to change drawer icon
  • how to pause progressbar in android
  • Styling composite views
  • Android, Eclipse: My app crashes on older API versions
  • Parcelable with arraylist<string> passing value from activity to fragment android
  • Why is there an extra part when parseUri() a String?
  • onItemClick and Toast don't work in a listfragment
  • Get input text with customview without edittext android
  • Getting value from the listview with custom adpter of selected checkbox to the activity
  • calculate value based on current and previous row in cursor android
  • How to save hashmap to shared preference?
  • How to Handle backPress with Fragment
  • DrawAllocation: Memory allocations within drawing code
  • Can I send Audio messages / notification in Android Auto?
  • Need layout design suggestion
  • Parse.com : Android how to store Image ParseFile in ParseObject in Offline Mode
  • Android Facebook LoginButton class not found
  • How to start another Activity using Button inside the Fragment
  • How to display video after getting from json?
  • Short black flashs when switching fragments in navigation drawer
  • Phonegap plugin does not work using remote build
  • Scrolling between dates in android
  • How to build system apps in Android Studio?
  • How to Display Dates in Calendar View from Database
  • How to give id of every fragment in and use it Tab Fragment android
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org