Skip to content

Instantly share code, notes, and snippets.

Created April 30, 2015 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5ae47fa60773dc6d023a to your computer and use it in GitHub Desktop.
Save anonymous/5ae47fa60773dc6d023a to your computer and use it in GitHub Desktop.
public class Server extends Thread {
private final String LOG_TAG = "Server";
private final int DEFAULT_PORT = 57646;
private ServerSocket serverSocket = null;
@Override
public void run() {
super.run();
Socket socket = null;
try {
serverSocket = new ServerSocket(DEFAULT_PORT);
} catch (IOException e) {
e.printStackTrace();
return;
}
while (!isInterrupted()) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
Log.e(LOG_TAG, "I/O error: " + e);
}
if(socket != null)
new ServerEcho(socket).start();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void terminate(){
interrupt();
if(serverSocket != null){
//Иначе получим android.os.NetworkOnMainThreadException
new Thread(new Runnable() {
@Override
public void run() {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
try {
join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment