I try to start the server, but when I press the button, nothing happens and is not displayed. Tell me how to implement the server start when you click on the button in the emulator?

Class MainActivity:

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Server server = new Server(); Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); button.setOnClickListener(this); } public void onClick(View v){ switch (v.getId()){ case R.id.button: server.startServer(); break; } } } 

Server class:

 import java.net.*; import java.io.*; public class Server { public void startServer() { int port = 6666; try { ServerSocket ss = new ServerSocket(port); System.out.println("Waiting for a client..."); Socket socket = ss.accept(); System.out.println("Got a client"); System.out.println(); InputStream sin = socket.getInputStream(); OutputStream sout = socket.getOutputStream(); DataInputStream in = new DataInputStream(sin); DataOutputStream out = new DataOutputStream(sout); String line = null; while(true) { line = in.readUTF(); System.out.println("The dumb client just sent me this line : " + line); System.out.println("I'm sending it back..."); out.writeUTF(line); out.flush(); System.out.println("Waiting for the next line..."); System.out.println(); } } catch(Exception x) { x.printStackTrace(); } } } 
  • your code is working, you just don't put it there. instead of System.out.println("Some string") , use Log.d("Server", "Some string"); - Lex Hobbit
  • Working with the network in a UI stream? - post_zeew
  • Thank! You are right - Tenday

1 answer 1

Understood. There were three problems:

  1. It was necessary to use Log.d("Server", "Some string"); to display messages
  2. Forgot to add <uses-permission android:name="android.permission.INTERNET"/> to manifest
  3. You cannot perform network operations in the main thread. (Read more https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception )