Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class Server implements Runnable {
- private ExecutorService executors;
- private ServerSocket serverSocket;
- private Thread thread;
- private volatile boolean running;
- public void init(int port) throws IOException {
- this.setRunning(true);
- this.executors = Executors.newFixedThreadPool(10);
- this.serverSocket = new ServerSocket(port);
- this.thread = new Thread(this);
- this.thread.start();
- }
- @Override
- public void run() {
- while (isRunning()) {
- try {
- Socket socket = serverSocket.accept();
- Worker worker = new Worker(socket);
- executors.submit(worker);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public Thread getThread() {
- return thread;
- }
- public boolean isRunning() {
- return running;
- }
- public void setRunning(boolean running) {
- this.running = running;
- }
- private class Worker implements Runnable {
- private final Socket socket;
- private final DataInputStream in;
- private final DataOutputStream out;
- public Worker(Socket socket) throws IOException {
- this.socket = socket;
- this.in = new DataInputStream(socket.getInputStream());
- this.out = new DataOutputStream(socket.getOutputStream());
- }
- public void run() {
- try {
- while (isRunning()) {
- String request = in.readUTF();
- out.writeUTF(request);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement