简体   繁体   中英

Android java : How to send message from server to a specific client any time

I tried to send message from server to client but if i send message the client needs to connect again or println again... So how does it work? I tried to println again from server to client but the client wont receive it.

So how to send message to a specific client at any time.

Server:

package server.server.com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;

public class Server extends Thread {
    private static ServerSocket serverSocket;
    public static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;
    static InputStream is;
    static OutputStream os;
    static byte[] buf;
    static BufferedReader reader;
    static BufferedWriter writer;
    static double ConsoleMessage;
    public static String output;
    static BufferedReader bufferedReader2;


    public static void main(String[] args) {

        try {
            serverSocket = new ServerSocket(12345);

        } catch (IOException e) {
            System.out.println("Could not listen on port: 12345");
        }

        System.out.println("Server started. Listening to the port 12345");

        while (true) {

            try {

                clientSocket = serverSocket.accept();
                inputStreamReader = new InputStreamReader(
                        clientSocket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader);


                PrintWriter out = new PrintWriter(
                        clientSocket.getOutputStream(), true);
                InputStream inputStream = new ByteArrayInputStream(
                        bufferedReader.readLine().getBytes(
                                Charset.forName("UTF-8")));
                bufferedReader2 = new BufferedReader(new InputStreamReader(
                        inputStream));
                output = bufferedReader2.readLine();
                System.out.println(output);

                out.flush();
                out.close();
                inputStreamReader.close();
                clientSocket.close();

            } catch (IOException ex) {
                System.out.println("Problem in message reading");
            }
        }

    }
}

Client:

  client = new Socket();
  client.connect(
      new InetSocketAddress(
         "IP-ADDRESS",
         PORT),
         5000);
   in = new BufferedReader(
   new InputStreamReader(
   client.getInputStream()));
       printlng = new PrintWriter(
           client.getOutputStream());
       printlng.println(mLongitude);
       printlng.flush();

       try {
           if ((Response = in
           .readLine()) != null) {

....

You should take a look at http://developer.android.com/google/gcm/index.html . Maybe you could take advantage of push notifications in your app.

Maybe you can do something like this

Server:

private boolean sendMessage(final String msg, final String dstIp, final int dstPort) {

    DatagramSocket sendSocket = null;

    try {
        sendSocket = new DatagramSocket();

        final InetAddress local = InetAddress.getByName(dstIp);
        final int msg_length = msg.length();
        final byte[] message1 = msg.getBytes();

        final DatagramPacket sendPacket = new DatagramPacket(message1,
                msg_length, local, dstPort);
        sendSocket.send(sendPacket);

    } catch (final Exception e) {
        e.printStackTrace();
        return false;
    } finally {

        if (sendSocket != null) {
            sendSocket.disconnect();
            sendSocket.close();
            sendSocket = null;
        }
    }
    return true;
}

Client:

public static void receiveMessage() {

    if ((socket == null) || socket.isClosed()) {

            socket = new DatagramSocket(BROADCAST_PORT);
            socket.setSoTimeout(5000);

        } 

     try {
            idMsgs.clear();
            while ((socket != null) && !socket.isClosed()) {
                socket.setReuseAddress(true);
                socket.setSoTimeout(10000);

                try {
                    final byte[] receiveBuffer = new byte[sizepck];
                    final DatagramPacket packet = new DatagramPacket(
                            receiveBuffer, receiveBuffer.length);

                    socket.receive(packet);

                } catch (final SocketTimeoutException e) {

                } catch (final Throwable e) {

                }
            }

        } catch (final Throwable e1) {

            try {
                Thread.sleep(TIME_RETRY);
            } catch (final InterruptedException e) {
                e.printStackTrace();
            }
        }

        finally {
            if (socket != null) {
                socket.close();
            }
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM