我正在创建此聊天应用程序,用户可以在同一WiFi
上进行联系时进行通话。他们使用Network Service Discovery
检测对方(它的工作非常糟糕,有时他们并没有找到对方)。一旦他们在网络上看到对方,他们就可以开始对话了。我创建了这个类:
码
public class ChatConnection {
private ServerSocket serverSocket;
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
private String message = "";
private Thread serverThread;
@Inject
public ChatConnection() {
serverThread = new Thread(new ServerThread());
serverThread.start();
}
public Observable<Boolean> connectToServer(InetAddress host, int port)
{
return Observable.unsafeCreate(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
try {
if (socket != null) {
if (socket.isConnected()) {
socket.close();
}
socket = new Socket(host, port);
} else
socket = new Socket(host, port);
subscriber.onNext(socket.isConnected());
} catch (IOException e) {
subscriber.onError(e);
}
}
});
}
public Observable<String> observeServer() {
return Observable.unsafeCreate(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
while (!message.equals("##exit##")) {
message = dataInputStream.readUTF();
subscriber.onNext(message);
}
} catch (IOException e) {
subscriber.onError(e);
}
});
}
public Observable<Boolean> sendMessage(String message) {
return Observable.unsafeCreate(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
try {
dataOutputStream.writeUTF(message);
subscriber.onNext(true);
} catch (IOException e) {
subscriber.onError(e);
}
}
});
}
public int getLocalPort() {
return serverSocket.getLocalPort();
}
public void tearDown() {
try {
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
@Override
public void run() {
try {
serverSocket = new ServerSocket(0);
socket = serverSocket.accept();
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
dataInputStream = new DataInputStream(inputStream);
dataOutputStream = new DataOutputStream(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
问题是 observeServer()没有做任何事情,甚至设置内部的Log.d(...)也从未显示任何内容。我对java sockets
非常陌生。我想有人告诉我我做错了什么。谢谢。