Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package de.cloud.tammo.communication;
- import java.io.*;
- import java.net.*;
- import java.util.HashMap;
- /**
- * Created by Tammo on 26.06.2017.
- */
- public class Server {
- private int port;
- private Thread t;
- public ServerSocket serversocket;
- private HashMap<String, Handler> handler;
- private boolean running = false;
- public Server(int port) {
- this.port = port;
- handler = new HashMap<>();
- }
- public void start() {
- t = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- serversocket = new ServerSocket(port);
- running = true;
- while (running) {
- Socket s = serversocket.accept();
- ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
- try {
- Packet p = (Packet) ois.readObject();
- handler.get(p.getName()).handle(p, s);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- t.start();
- }
- public void stop() {
- running = false;
- try {
- serversocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- t.interrupt();
- }
- public void sendPacketWithTryCatch(Packet p, String host, int port) throws IOException, ConnectException {
- Socket s = new Socket(host, port);
- ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
- oos.writeObject(p);
- s.close();
- }
- public void sendPacket(Packet p, String host, int port){
- try {
- Socket s = new Socket(host, port);
- ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
- oos.writeObject(p);
- s.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void addHandler(String packetname, Handler h) {
- this.handler.put(packetname, h);
- }
- public HashMap<String, Handler> getHandler() {
- return handler;
- }
- public int getPort() {
- return port;
- }
- public void setPort(int port) {
- this.port = port;
- }
- public boolean getRunningState() {
- return this.running;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement