Advertisement
Guest User

Untitled

a guest
Aug 20th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.84 KB | None | 0 0
  1. package network;
  2.  
  3. import core.I18N;
  4. import core.msg.DisconnectMessage;
  5. import core.msg.ListenMessage;
  6. import core.msg.Message;
  7. import core.msg.MessageCenter;
  8. import core.msg.MessageSubscriber;
  9. import core.msg.NetworkMessage;
  10. import java.io.IOException;
  11. import java.io.ObjectInputStream;
  12. import java.net.ServerSocket;
  13. import java.net.Socket;
  14. import java.net.SocketException;
  15. import javax.swing.JOptionPane;
  16.  
  17. /**
  18. * Listens to port and delivers incoming messages to the MessageCenter
  19. *
  20. * @author Pieter Reuse
  21. * @version 1.1
  22. * @date 25-05-11
  23. */
  24. public class MessageReceiver implements MessageSubscriber {
  25.  
  26. //the socket that came out of ServerSocket(ConnectionManager.port).accept()
  27. //(or as parameter with receiveMessages(Socket socket)
  28. private static Socket lastSocket;
  29.  
  30. //the last input from the socket, needs to be a field to pass it on to inner class
  31. private static Object lastInput;
  32.  
  33. //the thread that listens for incoming requests
  34. private static Thread listenThread;
  35.  
  36. //the thread that processed input. Needs to be a field to check if it's null or not
  37. private static Thread inputThread;
  38.  
  39. //the inputStream from lastSocket
  40. private static ObjectInputStream inputStream;
  41.  
  42. //the serversocket that listens for incoming connectionrequests
  43. private static ServerSocket server;
  44.  
  45. //indicates if stop() is called or not (needed to know if a Disconnect-
  46. //Message should be called when inputStream throws exception or not)
  47. private static boolean stopping = false;
  48.  
  49. /**
  50. * constructor
  51. *
  52. * @effect MessageCenter.getInstance().subscribe(ListenMessage.class, this)
  53. */
  54. public MessageReceiver() {
  55. MessageCenter.getInstance().subscribe(ListenMessage.class, this);
  56. }
  57.  
  58. /**
  59. * listens for incoming connection requests
  60. * @throws UnsupportedOperationException when listenThread is not-null
  61. * or NetworkState.getState() is not DISCONNECTED
  62. * @post listenThread listens to serversocket.accept() (and is not null duh)
  63. */
  64. public static synchronized void listenForConnection() {
  65. if (listenThread != null) {
  66. //prevents listening two times
  67. throw new UnsupportedOperationException("allready listening for connections!");
  68. }
  69. if (NetworkState.getState()!=NetworkStateEnum.DISCONNECTED){
  70. throw new UnsupportedOperationException("not disconnected!");
  71. }
  72.  
  73. //set up a thread that does new ServerSocket(ConnectionManager.port).accept()
  74. //and run the thread
  75. listenThread = new Thread() {
  76.  
  77. @Override
  78. public void run() {
  79. try {
  80. server = new ServerSocket(ConnectionManager.port);
  81. lastSocket = server.accept();
  82. receiveMessages();
  83. } catch (SocketException ex) {
  84. //if closed by stop(), do nothing (certainly don't throw an exception!)
  85. } catch (IOException ex) {
  86. JOptionPane.showMessageDialog(null, I18N.get("couldn_listen") + ConnectionManager.port + " !", I18N.get("error"), JOptionPane.ERROR_MESSAGE);
  87. throw new UnsupportedOperationException(I18N.get("couldn_listen") + ConnectionManager.port + " !");
  88. }
  89. listenThread = null;
  90. }
  91. };
  92. listenThread.start();
  93. }
  94.  
  95. /**
  96. * stops listenThread and inputThread (by closing server, inputStream and lastSocket)
  97. * and sets them to null
  98. *
  99. * @post !old.listenThread.isAlive()
  100. * @post !old.inputThread.isAlive()
  101. * @post listenThread==null
  102. * @post inputThread==null
  103. */
  104. public synchronized static void stop() {
  105. //we are stopping. Don't send (additional) DisconnectMessages
  106. stopping=true;
  107.  
  108. //close server (try it), then listenThread should stop (if it were running)
  109. //then you can set it to null
  110. //(if it was allready null, it's not needed ofc
  111. try {
  112. if(listenThread!=null)server.close();
  113. } catch (IOException ex) {}
  114. listenThread = null;
  115.  
  116. //close inputStream and lastSocket (try it), then inputThread should stop
  117. //(if it were running), then you can set it to null
  118. //if allready null, not needed ofc
  119. if (inputThread != null) {
  120. try {
  121. inputStream.close();
  122. lastSocket.close();
  123. } catch (IOException ex) {
  124. }
  125. }
  126. inputThread = null;
  127.  
  128. //done stopping
  129. stopping=false;
  130. }
  131.  
  132. /**
  133. * does receiveMessages after setting lastSocket to socket
  134. *
  135. * @param socket: the Socket to receive messages from
  136. * @effect receiveMessages()
  137. * @post lastSocket==socket
  138. */
  139. public static synchronized void receiveMessages(Socket socket) {
  140. lastSocket=socket;
  141. receiveMessages();
  142. }
  143.  
  144. /**
  145. * processes ListenMessages
  146. * @effect listenForConnection()
  147. */
  148. public void process(Message m) {
  149. if(m.getClass().equals(ListenMessage.class)) listenForConnection();
  150. }
  151.  
  152. /**
  153. * Listens to the port socket and calls a new thread processing received messages
  154. *
  155. * @throws UnsupportedOperationException if either inputThread or lastSocket null
  156. * @effect new MessageSender(lastSocket)
  157. * @post inputThread is a new thread that listens for incoming Messages on lastSocket,
  158. * sets up a thread handling that message each time a messages comes in,
  159. * and runs both inner and outer thread
  160. */
  161. public static synchronized void receiveMessages() {
  162. //inputThread nor lastSocket should be null
  163. if (inputThread != null) {
  164. throw new UnsupportedOperationException("allready receiving messages!");
  165. }
  166. if (lastSocket == null) {
  167. throw new UnsupportedOperationException("no last connection request found!");
  168. }
  169. //send messages to the same socket
  170. MessageSender messageSender = new MessageSender(lastSocket);
  171.  
  172. //set up inputThread
  173. inputThread = new Thread() {
  174.  
  175. @Override
  176. public void run() {
  177. try {
  178. //stay receiving while that throws no exceptions (bad messages,
  179. //connection resets or the inputStream that gets closed)
  180. inputStream = new ObjectInputStream(lastSocket.getInputStream());
  181. boolean stayReceiving=true;
  182. while (stayReceiving) {
  183. try{lastInput = inputStream.readObject();}
  184. catch (Exception e){
  185. //something went wrong with receiving
  186. }
  187. //set up a new thread handling the message that came in
  188. Thread process = new Thread() {
  189.  
  190. @Override
  191. public void run() {
  192. NetworkMessage m = (NetworkMessage) lastInput;
  193. MessageCenter.getInstance().publish(m.getMessage());
  194. }
  195. };
  196. if(stayReceiving){
  197. //stop receiving when receiving a disconnectedmessage
  198. process.start();
  199. Message m = ((NetworkMessage) lastInput).getMessage();
  200. if(m.getClass().equals(DisconnectMessage.class)) stayReceiving=false;
  201. }
  202. }
  203. } catch (IOException e) {
  204. //e.printStackTrace();
  205. }
  206. }
  207. };
  208. //run the input-thread
  209. inputThread.start();
  210. }
  211.  
  212. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement