Created
April 30, 2015 09:41
-
-
Save anonymous/5ae47fa60773dc6d023a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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