Use Socket communication (one)

 

 

Use socket requires a server, I use the tomcat, like AS does not support Tomcat, and what a good recommendation server request, using Tomcat Quguan network to download, and then have to install the Java jdk, and then configure jak environment variables, and then configure Tomcat environment variables,

 

  

 

 

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Socket socket = new Socket("这里是你的本地ip地址,cmd输入ipconfig会显示", 8080);

                    if (socket.isConnected()) {

                        System.out.println("已连接");
                        OutputStream outputStream = socket.getOutputStream();
                        String message="你好  yiwangzhibujian";
                        outputStream.write(message.getBytes("UTF-8"));
                        System.out.println("写出到服务器");
                        outputStream.close();
                        socket.close();


                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();



    }
    }

Tomcat default port 8080, a network service can not be in the main thread, the thread is reopened a communications network, the server sends data to upper

 Also to declare rights

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Guess you like

Origin www.cnblogs.com/Ocean123123/p/10959202.html