Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package network;
- import core.I18N;
- import core.msg.DisconnectMessage;
- import core.msg.ListenMessage;
- import core.msg.Message;
- import core.msg.MessageCenter;
- import core.msg.MessageSubscriber;
- import core.msg.NetworkMessage;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.net.SocketException;
- import javax.swing.JOptionPane;
- /**
- * Listens to port and delivers incoming messages to the MessageCenter
- *
- * @author Pieter Reuse
- * @version 1.1
- * @date 25-05-11
- */
- public class MessageReceiver implements MessageSubscriber {
- //the socket that came out of ServerSocket(ConnectionManager.port).accept()
- //(or as parameter with receiveMessages(Socket socket)
- private static Socket lastSocket;
- //the last input from the socket, needs to be a field to pass it on to inner class
- private static Object lastInput;
- //the thread that listens for incoming requests
- private static Thread listenThread;
- //the thread that processed input. Needs to be a field to check if it's null or not
- private static Thread inputThread;
- //the inputStream from lastSocket
- private static ObjectInputStream inputStream;
- //the serversocket that listens for incoming connectionrequests
- private static ServerSocket server;
- //indicates if stop() is called or not (needed to know if a Disconnect-
- //Message should be called when inputStream throws exception or not)
- private static boolean stopping = false;
- /**
- * constructor
- *
- * @effect MessageCenter.getInstance().subscribe(ListenMessage.class, this)
- */
- public MessageReceiver() {
- MessageCenter.getInstance().subscribe(ListenMessage.class, this);
- }
- /**
- * listens for incoming connection requests
- * @throws UnsupportedOperationException when listenThread is not-null
- * or NetworkState.getState() is not DISCONNECTED
- * @post listenThread listens to serversocket.accept() (and is not null duh)
- */
- public static synchronized void listenForConnection() {
- if (listenThread != null) {
- //prevents listening two times
- throw new UnsupportedOperationException("allready listening for connections!");
- }
- if (NetworkState.getState()!=NetworkStateEnum.DISCONNECTED){
- throw new UnsupportedOperationException("not disconnected!");
- }
- //set up a thread that does new ServerSocket(ConnectionManager.port).accept()
- //and run the thread
- listenThread = new Thread() {
- @Override
- public void run() {
- try {
- server = new ServerSocket(ConnectionManager.port);
- lastSocket = server.accept();
- receiveMessages();
- } catch (SocketException ex) {
- //if closed by stop(), do nothing (certainly don't throw an exception!)
- } catch (IOException ex) {
- JOptionPane.showMessageDialog(null, I18N.get("couldn_listen") + ConnectionManager.port + " !", I18N.get("error"), JOptionPane.ERROR_MESSAGE);
- throw new UnsupportedOperationException(I18N.get("couldn_listen") + ConnectionManager.port + " !");
- }
- listenThread = null;
- }
- };
- listenThread.start();
- }
- /**
- * stops listenThread and inputThread (by closing server, inputStream and lastSocket)
- * and sets them to null
- *
- * @post !old.listenThread.isAlive()
- * @post !old.inputThread.isAlive()
- * @post listenThread==null
- * @post inputThread==null
- */
- public synchronized static void stop() {
- //we are stopping. Don't send (additional) DisconnectMessages
- stopping=true;
- //close server (try it), then listenThread should stop (if it were running)
- //then you can set it to null
- //(if it was allready null, it's not needed ofc
- try {
- if(listenThread!=null)server.close();
- } catch (IOException ex) {}
- listenThread = null;
- //close inputStream and lastSocket (try it), then inputThread should stop
- //(if it were running), then you can set it to null
- //if allready null, not needed ofc
- if (inputThread != null) {
- try {
- inputStream.close();
- lastSocket.close();
- } catch (IOException ex) {
- }
- }
- inputThread = null;
- //done stopping
- stopping=false;
- }
- /**
- * does receiveMessages after setting lastSocket to socket
- *
- * @param socket: the Socket to receive messages from
- * @effect receiveMessages()
- * @post lastSocket==socket
- */
- public static synchronized void receiveMessages(Socket socket) {
- lastSocket=socket;
- receiveMessages();
- }
- /**
- * processes ListenMessages
- * @effect listenForConnection()
- */
- public void process(Message m) {
- if(m.getClass().equals(ListenMessage.class)) listenForConnection();
- }
- /**
- * Listens to the port socket and calls a new thread processing received messages
- *
- * @throws UnsupportedOperationException if either inputThread or lastSocket null
- * @effect new MessageSender(lastSocket)
- * @post inputThread is a new thread that listens for incoming Messages on lastSocket,
- * sets up a thread handling that message each time a messages comes in,
- * and runs both inner and outer thread
- */
- public static synchronized void receiveMessages() {
- //inputThread nor lastSocket should be null
- if (inputThread != null) {
- throw new UnsupportedOperationException("allready receiving messages!");
- }
- if (lastSocket == null) {
- throw new UnsupportedOperationException("no last connection request found!");
- }
- //send messages to the same socket
- MessageSender messageSender = new MessageSender(lastSocket);
- //set up inputThread
- inputThread = new Thread() {
- @Override
- public void run() {
- try {
- //stay receiving while that throws no exceptions (bad messages,
- //connection resets or the inputStream that gets closed)
- inputStream = new ObjectInputStream(lastSocket.getInputStream());
- boolean stayReceiving=true;
- while (stayReceiving) {
- try{lastInput = inputStream.readObject();}
- catch (Exception e){
- //something went wrong with receiving
- }
- //set up a new thread handling the message that came in
- Thread process = new Thread() {
- @Override
- public void run() {
- NetworkMessage m = (NetworkMessage) lastInput;
- MessageCenter.getInstance().publish(m.getMessage());
- }
- };
- if(stayReceiving){
- //stop receiving when receiving a disconnectedmessage
- process.start();
- Message m = ((NetworkMessage) lastInput).getMessage();
- if(m.getClass().equals(DisconnectMessage.class)) stayReceiving=false;
- }
- }
- } catch (IOException e) {
- //e.printStackTrace();
- }
- }
- };
- //run the input-thread
- inputThread.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement