我有一张wifi sd卡,在我用相机拍摄照片后,会向我发送TCP包,其中包含有关新内存图像的信息。
在终端上,我可以使用此netcat命令读取输入流。 netcat连接到ip 192.168.11.254并侦听端口5566.第二行是我收到的图像路径。
$ nc 192.168.11.254 5566
>/mnt/sd/DCIM/109_0302/IMGP0101.JPG
在我的应用程序上,我有一个Java客户端套接字,它连接到同一个ip和端口。但我没有像netcat那样收到输入流,没有任何反应。
void startListenForTCP (){
Thread TCPListenerThread = new Thread(new Runnable() {
@Override
public void run() {
Boolean run = true;
String serverMessage = null;
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName("192.168.11.254");
Socket clientSocket = new Socket(serverAddr, 5566);
try{
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (run) {
serverMessage = in.readLine();
mHandler.post(new DisplayToast(context, "TCP : " + serverMessage));
}
} catch(UnknownHostException e) {
mHandler.post(new DisplayToast(context, "UnknownHostException"));
} catch(IOException e) {
mHandler.post(new DisplayToast(context, "IOException"));
} finally {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
TCPListenerThread.start();
}
答案 0 :(得分:5)
尝试这可能有效
删除这两行:
serverAddr = InetAddress.getByName("192.168.11.254");
Socket clientSocket = new Socket(serverAddr, 5566);
添加以下行:
Socket clientSocket = new Socket("192.168.11.254", 5566);
删除此代码:
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (run) {
serverMessage = in.readLine();
mHandler.post(new DisplayToast(context, "TCP : " + serverMessage));
}
}
添加此代码:
try {
char[] buffer = new char[2048];
int charsRead = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while ((charsRead = in.read(buffer)) != -1) {
String message = new String(buffer).substring(0, charsRead);
Log.e("In While", "msg :"+message);
}
}
答案 1 :(得分:4)
BufferedReader.readLine()
状态的javadoc:
阅读一行文字。一条线被认为是任何一条线终止的 换行符('\ n'),回车符('\ r')或回车符 然后立即换行。
如果卡片没有发送某种行尾,则此方法永远不会返回。尝试从clientSocket.getInputStream()
读取directyl。这不会做任何缓冲。