我在试图从套接字读取数据时生气。我尝试了所有这些,我认为我的代码应该可以工作,但没有。
我的目的是只在onCreate上运行以下方法。首先,我创建一个Thread来运行与网络相关的所有事情。然后,我创建了scoket对象,然后我读取了socket的输入流。在这一刻,在无限循环中,我使用readLine读取输入流,如this answer所述。最后,我根据套接字提供的数据做我想做的事。
我不知道服务器会发送多少数据。它会在json中,但这并不重要。
这是我的代码
public void receiveMsgs(){
new Thread(new Runnable(){
@Override
public void run() {
BufferedReader in = null;
try {
Log.d("NETWORK-RECEIVE", "Trying to connect to socket...");
Socket socket;
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(socket.isConnected()){
Log.d("NETWORK-RECEIVE", "The connection have been stablished");
}
} catch (IOException e) {
e.printStackTrace();
Log.d("NETWORK-RECEIVE", "Something goes wrong: IOException");
}
while(true){
String msg = null;
try {
StringBuilder total = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
total.append(line);
}
msg = total.toString();
Log.d("NETWORK-RECEIVE","Message readed!:"+msg);
} catch (IOException e) {
e.printStackTrace();
Log.d("NETWORK-RECEIVE", "Something goes wrong: IOException");
}
if(msg == null){
Log.d("NETWORK-RECEIVE", "Message is null");
break;
}
else{
//Do what I want
Log.d("NETWORK-RECEIVE", "something");
}
}
}
}).start();
}
答案 0 :(得分:1)
看看广场的OKHttp还是Retrofit?
http://square.github.io/okhttp/#examples
&安培;
http://square.github.io/retrofit/
似乎比套接字更容易。你真的需要套接字吗?