public class BackgroundService extends Service{
ServerSocket server = null;
Socket socketClient = null;
private static final String TAG = BackgroundService.class.getSimpleName();
Thread socketThread;
int temp =0;
@Override
public IBinder onBind(Intent intent) {
if (BackgroundService.class.getName().equals(intent.getAction())) {
Log.d(TAG, "Bound by intent " + intent);
return apiEndpoint;
} else {
return null;
}
}
private final Object latestIncomingMessage = new Object();
private List<MessageCollectorListener> listeners = new ArrayList<MessageCollectorListener>();
private Message message = new Message(" ");
private MessageCollectorApi.Stub apiEndpoint = new MessageCollectorApi.Stub() {
@Override
public void removeListener(MessageCollectorListener listener) throws RemoteException {
synchronized (listener) {
listeners.remove(listener);
}
}
@Override
public Message getValue() throws RemoteException {
synchronized (latestIncomingMessage) {
return message;
}
}
@Override
public void addListener(MessageCollectorListener listener) throws RemoteException {
synchronized (listener) {
listeners.add(listener);
}
}
};
@Override
public void onCreate() {
super.onCreate();
socketThread = new Thread()
{
@Override
public void run()
{
try {
server = new ServerSocket(8080);
} catch (IOException e2) {
e2.printStackTrace();
};
while(true){
try {
socketClient = server.accept();
InputStream is = socketClient.getInputStream();
DataOutputStream os = new DataOutputStream(socketClient.getOutputStream());
InputStreamReader isr = new InputStreamReader(is);
char[] buff = new char[10];
BufferedReader br = new BufferedReader(isr);
br.read(buff);
synchronized (latestIncomingMessage) {
message.setValue(String.valueOf(buff));
}
synchronized (listeners) {
for (MessageCollectorListener listener : listeners) {
try {
listener.handleUpdatedMessages();
} catch (RemoteException e) {
Log.w(TAG, "Failed to notify listener " + listener, e);
}
}
}
buff = new char[10];
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
socketThread.start();
}
@Override
public void onDestroy() {
super.onDestroy();
socketThread.destroy();
}
}
答案 0 :(得分:0)
由于服务器正在主线程中侦听,因此在服务器与客户端建立连接之前,方法onCreate
才会完成,并且onCreate
会超时。为避免这种情况,请在另一个线程中运行服务器。
要读取缓冲区而不是readline
,您可以执行以下操作:
char buff = new char[MAX_PACKET_SIZE];
BufferedReader br = new BufferedReader(new InputStream(socket.getInputStream()));
br.read(buff);