使用Service或IntentService进行Android ClientServer Socket通信

使用Service或IntentService进行Android ClientServer Socket通信,第1张

概述到目前为止,我能够在一个 Android设备(wifi tethering / hotspot)上启动服务器,并让客户端(另一个android)连接并向服务器发送消息.然后服务器回复了那个.我意识到我需要一种方法来保持服​​务器监听客户端,即使聊天应用程序没有运行.客户端应该能够发送消息,服务器应该收到此消息.我应该使用Service或IntentService来实现此目的吗?我不能从AsyncT 到目前为止,我能够在一个 Android设备(wifi tethering / hotspot)上启动服务器,并让客户端(另一个androID)连接并向服务器发送消息.然后服务器回复了那个.我意识到我需要一种方法来保持服​​务器监听客户端,即使聊天应用程序没有运行.客户端应该能够发送消息,服务器应该收到此消息.我应该使用Service或IntentService来实现此目的吗?我不能从AsyncTask&服务……如何实现这个?一些示例代码会很棒.

这就是我的服务器的样子:

public class Server extends AsyncTask<Integer,VoID,Socket> {    private ServerSocket serverSocket;    private TextVIEw textVIEw;    private String incomingMsg;    private String outgoingMsg;    public Server(TextVIEw textVIEw) {        this.textVIEw = textVIEw;    }    public voID closeServer() {        try {            serverSocket.close();        } catch (IOException e) {            Log.d("Server","Closung the server caused a problem");            e.printstacktrace();        }           }    @OverrIDe    protected Socket doInBackground(Integer... params) {        try {            serverSocket = new ServerSocket(params[0]);                   //accept connections            Socket socket = serverSocket.accept();            BuffereDWriter out = new BuffereDWriter(new OutputStreamWriter(socket.getoutputStream()));            BufferedReader in = new BufferedReader(new inputStreamReader(socket.getinputStream()));            incomingMsg = in.readline() + System.getProperty("line.separator");            //send a message            outgoingMsg = "You are connected to the Server" + System.getProperty("line.separator");            out.write(outgoingMsg);            out.flush();            return socket;        } catch (InterruptedioException e) {            //if timeout occurs            e.printstacktrace();        } catch (IOException e) {            e.printstacktrace();        } //      finally {//          if (serverSocket != null) {//              try {//                  serverSocket.close();//              } catch (IOException e) {//                  e.printstacktrace();//              }//          }//      }        return null;    }    protected voID onPostExecute(Socket socket) {        if(socket != null) {            try {                Log.i("Server","Server received: " + incomingMsg);                textVIEw.setText("Server received: " + incomingMsg + "\n");                textVIEw.append("Server sent: " + outgoingMsg + "\n");                Log.i("Server","Server sent: " + outgoingMsg);                socket.close();            } catch (IOException e) {                // Todo auto-generated catch block                e.printstacktrace();            }        } else {            Log.d("Server","Can't communicate with the clIEnt!");        }    }}

这是我的客户:

public class ClIEnt extends AsyncTask<Integer,Socket> {    private WifiManager wifi;    private Context context;    private String outMsg;    private String inMsg;    public ClIEnt(Context context,WifiManager wifiManager) {        this.context = context;        this.wifi = wifiManager;    }    @OverrIDe    protected Socket doInBackground(Integer... params) {        try {            String gateway = intToIp(wifi.getDhcpInfo().gateway);            Socket socket = new Socket(gateway,params[0]);            BufferedReader in = new BufferedReader(new inputStreamReader(socket.getinputStream()));            BuffereDWriter out = new BuffereDWriter(new OutputStreamWriter(socket.getoutputStream()));            String ipadress = intToIp(wifi.getConnectionInfo().getIpAddress());            outMsg = ",ClIEnt " + ipadress +" is connecting!" + System.getProperty("line.separator");             out.write(outMsg);            out.flush();            //accept server response            inMsg = in.readline() + System.getProperty("line.separator");            return socket;        } catch (UnkNownHostException e) {            e.printstacktrace();        } catch (IOException e) {            e.printstacktrace();        }        return null;     }    public String intToIp(int addr) {        return  ((addr & 0xFF) + "." +                 ((addr >>>= 8) & 0xFF) + "." +                 ((addr >>>= 8) & 0xFF) + "." +                 ((addr >>>= 8) & 0xFF));    }    protected voID onPostExecute(Socket socket) {        if(socket != null) {            Log.i("ClIEnt","ClIEnt sent: " + outMsg);            Toast.makeText(context,"\nClIEnt sent: " + outMsg + "\n",Toast.LENGTH_LONG).show();            Log.i("ClIEnt","ClIEnt received: " + inMsg);            Toast.makeText(context,"ClIEnt received: " + inMsg + "\n",Toast.LENGTH_LONG).show();        } else {            Log.d("ClIEnt","Can't connect to server!");            Toast.makeText(context,"Can't connect to server!",Toast.LENGTH_LONG).show();        }               }}

如何从服务器中取出服务?客户应该也是服务吗?

解决方法 使用服务但忘记了AsyncTask.让您的服务启动您的通用线程( https://developer.android.com/reference/java/lang/Thread.html)并设置您的套接字侦听器.此服务甚至可以处理消息的发送(通过以下链接中涵盖的众多选项之一).

不要忘记在服务的onDestroy()中正确清理Threads.

另请注意,如果您希望应用程序继续接收来自其他客户端的消息,则需要确保将服务强制进入前台(请参阅http://developer.android.com/reference/android/app/Service.html#startForeground(int,androID.app.Notification).但是,这不是万无一失的,您的服务仍然可以被杀死.

这就是为什么人们倾向于使用托管在某个专用盒子上的服务器而不是每个单独的设备……

总结

以上是内存溢出为你收集整理的使用Service或IntentService进行Android Client / Server Socket通信全部内容,希望文章能够帮你解决使用Service或IntentService进行Android Client / Server Socket通信所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1127418.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存