简体   繁体   English

Java Android套接字线程

[英]Java Android Sockets Threading

I've a client class which tries to connect to a server. 我有一个尝试连接到服务器的客户端类。 But as you know you can't execute network operations on the Main UI thread. 但是您知道您无法在Main UI线程上执行网络操作。 So I've to create different threads for each operation. 因此,我必须为每个操作创建不同的线程。

Current code: 当前代码:

 package com.example.justus.rocchat; import android.os.AsyncTask; import android.util.JsonWriter; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.net.URL; import java.net.UnknownHostException; /** * Created by justus on 13-1-2015. */ public class Client { private String name; private int port; private String hostAddress; private Socket socketClient; private MainActivity mainActivity; public boolean isConnected; public Client(MainActivity mainActivity, String hostAdress, int port) { this.hostAddress = hostAdress; this.port = port; this.mainActivity = mainActivity; } public void send(final byte[] data) { Thread sendThread = new Thread(new Runnable() { public void run() { try { DataOutputStream out = new DataOutputStream(socketClient.getOutputStream()); out.write(data); System.out.println("writed data"); } catch (IOException ex) { } } }); sendThread.start(); } public void connect() { Thread connectThread = new Thread(new Runnable() { public void run() { try { System.out.println("trying to connect"); socketClient = new Socket(hostAddress, port); isConnected = true; } catch(UnknownHostException ex) { System.out.println("ex:" + ex.getMessage()); } catch (IOException ex) { System.out.println("ex:" + ex.getMessage()); } } }); connectThread.start(); } } 

Isn't this a little to much? 这不是很多吗? Are there any better ways to handle this operations? 有没有更好的方法来处理此操作? Already thanks for your time. 感谢您的宝贵时间。

AsyncTask is the accepted way of handling asynchronous operations. AsyncTask是处理异步操作的公认方法。 It is a wrapper around the Thread class and is part of the Android SDK. 它是Thread类的包装,是Android SDK的一部分。 They should only be used for operations that last under a few seconds, for longer operations you should use a Service. 它们只能用于持续几秒钟的操作,对于更长的操作,您应该使用服务。

developer.android.com/reference/android/os/AsyncTask.html developer.android.com/reference/android/os/AsyncTask.html

There are 2 options that you have 您有2个选择

  1. Use AsyncTask - much easier, object oriented that using threads but only for shortlived tasks (under 30 secs) 使用AsyncTask-比使用线程更轻松,面向对象,但仅适用于短期任务(30秒以内)
  2. Use RoboSpice - https://github.com/stephanenicolas/robospice 使用RoboSpice- https://github.com/stephanenicolas/robospice
    Of the two, I prefer RoboSpice 在这两者中,我更喜欢RoboSpice

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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