我有一张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();
}
解决方法:
试试这可能有效
步骤1
删除这两行:
serverAddr = InetAddress.getByName("192.168.11.254");
Socket clientSocket = new Socket(serverAddr, 5566);
添加此行:
Socket clientSocket = new Socket("192.168.11.254", 5566);
第2步
删除此代码:
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);
}
}
标签:android,java,sockets,tcp
来源: https://codeday.me/bug/20190722/1507529.html