android的tcp连接不能再主线程里,必须new一个线程,在新线程里完成各种动作。 什么bufferedreader的实在是调不通,用Inputstream倒是简单明了,适合和esp单片机通讯。 public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); EdgeToEdge.enable(this); setContentView(R.layout.activity_main); ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); return insets; }); } public void connectit(View view) throws IOException { Thread t=new Thread(new Runnable() { @Override public void run() { OutputStream ou; Socket cs; try { cs=new Socket("192.168.1.18",8268); ou=cs.getOutputStream(); byte[] sendStr="My first app,Bona.".getBytes(); ou.write(sendStr,0,sendStr.length); } catch (IOException e) { throw new RuntimeException(e); } try{ if(ou!=null){ ou.close(); } if(cs!=null){ cs.close();; } }catch (Exception e){ e.printStackTrace(); } } }); t.start(); } }
第一个Android(java)程序,连接局域网服务器
于 2024-07-10 20:09:08 首次发布