我想从Android应用程序向笔记本电脑发送字符串数据。 我在本地路由器wifi下将应用程序用作客户端,将笔记本电脑用作服务器。 这是我的代码:-
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private Socket client;
private Button button;
private EditText edit;
private String IP ="";
private int PORT = ;
private String result;
private String msg_received="";
private TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button); // the send button
edit = findViewById(R.id.editText); //text view
text = findViewById(R.id.textview);
sentdata();
}
private void sentdata() {
myTask mt = new myTask();
mt.execute();
}
class myTask extends AsyncTask<Void,Void,Void> {
@Override
protected Void doInBackground(Void... voids) {
try {
client = new Socket(IP,PORT);
while (true) {
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
result = edit.getText().toString();
text.setText(result);
DataOutputStream DOS = new DataOutputStream(client.getOutputStream());
DOS.writeUTF(result);
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}});
DataInputStream DIS = new DataInputStream(client.getInputStream());
if(DIS.available() != 0) {
msg_received = DIS.readUTF();
Log.d("msg", msg_received);
text.setText(msg_received);
}
if(msg_received.equals("bye")){
break;}
}
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
我的应用终止于 DOS.writeUTF(结果) DOS.readUTF() 当我不使用按钮单击并使用senddata作为按钮功能时
并注释getdata部分,然后它成功发送数据。
我想将数据从应用程序发送到便携式计算机,并从便携式计算机到应用程序实时接收数据。例如,如果更改给定数据并按下按钮,我会将数据发送到便携式计算机,当我从便携式计算机发送数据时,我会在应用程序上接收数据显示在textview中。