我正在开发一个TCP / IP套接字程序,以将Android手机与服务器PC连接起来。
我创建了一个简单的回声程序。
连接到服务器后,我可以发送注册命令而不会出现任何问题/延迟/挂起。
使用缓冲读取器接收数据后,我将数据传递给主要活动中的函数,实习生通过写入OutputStream将这些数据发送给服务器。当我的客户端发送此数据时,我的服务器挂起(忙碌等待->我的猜测),但是5秒钟后,它恢复了正常运行并成功接收了数据。甚至我的工作线程(AsyncTask)也挂起,这很明显,因为与其他消息相比,它们在Logcat中显示消息的时间明显延迟。
Android Studio 3.3.1
目标API级别:> = 26(8.0奥利奥)
TCP测试服务器-Hercules
@SuppressLint("StaticFieldLeak")
public void connect(){
new AsyncTask<Void, Void, Boolean>(){
@Override
protected Boolean doInBackground(Void... voids) {
try {
socket = new Socket(ip, portNo);
out = socket.getOutputStream();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
socketAlive.set(true);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
if(result){
sendData("RegisterDevice:<ip>:<mac>");
readerThread();
}
else{
socketAlive.set(false);
reconnect();
}
}
}.execute();
}
@SuppressLint("StaticFieldLeak")
public void sendData(final String data){
if(this.socket == null || this.socket.isClosed() )
{
//Unable to send data as output is closed returning
return;
}
new AsyncTask<String, Void, Boolean>(){
@Override
protected Boolean doInBackground(String... writeString) {
try {
out.write(writeString [0] .getBytes()); //->>将服务器套接字设置为 挂
//out.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
if(!result) {
reconnect();
sendData(data);
}
}
}.execute(data);
}
@SuppressLint("StaticFieldLeak")
public void readerThread(){
if(this.socket.isClosed())
{
//Unable to recieve data as output is closed returning
return;
}
new AsyncTask<Void, Void, Boolean>(){
@Override
protected Boolean doInBackground(Void... voids) {
try {
Arrays.fill(readBuffer, '\0');
//in.read(readBuffer, 0, Ethernet.TCP_READ_BUFFER_SIZE);//8192
in.read(readBuffer);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
if(result) {
//dataRead = String.copyValueOf(readBuffer, 0, Ethernet.TCP_READ_BUFFER_SIZE);
String str = String.copyValueOf(readBuffer);
str.trim();
Log.i("Test", "Test");
mainActivity.processEthernetData(String.copyValueOf(readBuffer, 0, Ethernet.TCP_READ_BUFFER_SIZE));
Log.i("ReadInfo", String.copyValueOf(readBuffer, 0, Ethernet.TCP_READ_BUFFER_SIZE));
readerThread();
}
else {
reconnect();
}
}
}.execute();
}
public void processEthernetData(final String protcol){
eth.sendData(protcol);
}
答案 0 :(得分:0)
问题是由
引起的 mainActivity.processEthernetData(String.copyValueOf(readBuffer, 0, Ethernet.TCP_READ_BUFFER_SIZE));
显然,创建并传递给函数的字符串的顺序为TCP_READ_BUFFER_SIZE
,其值为8192。当通过TCP / IP传输这么大的字符串时,它导致服务器暂时挂起,直到接收到完整的数据为止。
我通过将行更改为
解决了该错误mainActivity.processEthernetData(String.copyValueOf(readBuffer, 0, ethernetBytesRead));