Android Socket and JavaServerSocket connection problem

Code:

Java server-side code:

import java.io.*;
import java.net.*;

public class TCPS{      public static void main(String[] args) throws Exception {             ServerSocket server = new ServerSocket(6666);                        System.out.println("The server is ready .......");                         Socket client = server.accept();             System.out.println("Connected successfully");                   }

            




            

}

Android code:

Xml:

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mirana.socket.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_constraintTop_creator="1"
        android:layout_marginStart="132dp"
        android:layout_marginTop="154dp"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginLeft="132dp" />
</android.support.constraint.ConstraintLayout>

MainActivity.java:

 

package com.example.mirana.socket;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.*;
import java.net.*;

public class MainActivity extends AppCompatActivity {
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            Runner1  runner1=new Runner1();
                Thread thread=new Thread(runner1);
                thread.start();

            }
        });
    }
}
class Runner1 implements Runnable{
    public void run(){
        try{
            Socket socket=new Socket("39.105.4.*",6666);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

note:

Add permissions (<uses-permission android:name="android.permission.INTERNET"/>), the permissions should be added at the specified location.

This permission must be added to the position of the red arrow in the middle, otherwise the ServerSocket cannot be connected, because this problem wastes a long time.

Then open the ServiceSocket and then open the Android and click the Button to connect.

Guess you like

Origin blog.csdn.net/weixin_41967600/article/details/80948764