Guest User

server example

a guest
Aug 22nd, 2019
113
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. package G8R.app;
  3.  
  4. import java.io.IOException;
  5. import java.net.DatagramSocket;
  6. import java.net.ServerSocket;
  7. import java.net.Socket;
  8. import java.net.SocketException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.Scanner;
  12. import java.util.logging.*;
  13.  
  14. import G8R.serialization.*;
  15. import N4M.serialization.*;
  16. import N4M.app.N4MServer;
  17.  
  18. /**
  19. * G8RServer
  20. */
  21. public class G8RServer {
  22.  
  23. // G8R Logs
  24. private static String CONNECTIONLOG = "connections.log";
  25.  
  26. /**
  27. * getServerSocket
  28. * Returns a TCP ServerSocket connected to the port if it can
  29. * @param port Port number to connect, between 0 to 65535 inclusive
  30. * @return ServerSocket connected to
  31. * @throws IOException if I/O error when opening socket
  32. */
  33. private static ServerSocket getServerSocket(int port) throws IOException {
  34. ServerSocket retSocket = null;
  35. try {
  36. retSocket = new ServerSocket(port);
  37. }
  38. catch(IOException e){
  39. System.err.println("ERROR: I/O error when opening socket");
  40. throw e;
  41. }
  42. catch(IllegalArgumentException e) {
  43. System.err.println(
  44. "ERROR: Port parameter outside of range [0,65535]");
  45. throw e;
  46. }
  47. return retSocket;
  48. }
  49.  
  50. /**
  51. * G8RServer implementation
  52. * Runs TCP Poll application from Program 1
  53. * Runs UDP Access Count application from Program 5
  54. * @author Austin Lau
  55. * @param args array arguments, args[0] = port, args[1] = numThreads
  56. */
  57. public static void main(String[] args) throws IOException{
  58. // Confirm correct number of arguements
  59. if (args.length != 2) {
  60. throw new IllegalArgumentException(
  61. "Parameter(s): <Port> <NumThreads>");
  62. }
  63.  
  64. // Port Number
  65. int serverPort = Integer.parseInt(args[0]);
  66.  
  67. // Number of threads
  68. int numThreads = Integer.parseInt(args[1]);
  69. if (numThreads < 1) {
  70. throw new IllegalArgumentException(
  71. "Size of thread pool must be greater than 0");
  72. }
  73.  
  74. // Create a TCP server socket to accept client connection requests
  75. ServerSocket serverSock = getServerSocket(serverPort);
  76. // Set to reuse addresses (See SO_REUSEADDR)
  77. serverSock.setReuseAddress(true);
  78.  
  79. // G8R Logging Information
  80. final Logger g8rLogger = Logger.getLogger(CONNECTIONLOG);
  81. FileHandler g8rFH = new FileHandler(CONNECTIONLOG);
  82. g8rLogger.addHandler(g8rFH);
  83. g8rFH.setFormatter(new SimpleFormatter());
  84.  
  85. System.out.println("Starting server on port " + args[0]);
  86.  
  87. // N4M Server
  88. Thread n4mThread = new Thread() {
  89. public void run() {
  90. // Run forever
  91. for(;;) {
  92. try {
  93. // Establish the socket
  94. DatagramSocket socket = new DatagramSocket(serverPort);
  95. // Handle it somewhere else
  96. N4MServer.handleN4MServer(socket,serverPort,g8rLogger);
  97. // Close it
  98. socket.close();
  99. }
  100. catch (SocketException e) {
  101. e.printStackTrace();
  102. }
  103. }
  104. }
  105. };
  106. N4MServer.establishLogger();
  107. n4mThread.start();
  108.  
  109. // G8R Server
  110. for(int i = 0; i < numThreads; i++) {
  111. Thread g8rThread = new Thread() {
  112. public void run() {
  113. for(;;) {
  114. try{
  115. // TCP Socket
  116. Socket clientSocket = serverSock.accept();
  117. // Obtain Socket MessageInput and MessageOutput
  118. MessageInput mIn = new MessageInput(
  119. clientSocket.getInputStream());
  120. MessageOutput mOut = new MessageOutput(
  121. clientSocket.getOutputStream());
  122. // Recieve the response, output, and log
  123. handleG8RServer(
  124. clientSocket,mIn,mOut,g8rLogger);
  125. }catch(IOException ex) {
  126. g8rLogger.log(Level.WARNING,
  127. "Client accept failed", ex);
  128. }
  129. }
  130. }
  131. };
  132. // Run the thread
  133. g8rThread.start();
  134. }
  135. }
  136.  
  137. /**
  138. * handleG8RServer
  139. * Recieve input from input from the given socket
  140. * Log the issues found
  141. * Send a G8RRequest back to the client
  142. * @param clientSocket The Socket connected to
  143. * @param mIn MessageInput to read G8RRequest from
  144. * @parma mOut MessageOutput to write G8RResponse to
  145. * @param logger Log to record issues and warnings
  146. */
  147. private static void handleG8RServer(
  148. Socket clientSocket, MessageInput mIn,
  149. MessageOutput mOut,Logger logger){
  150. G8RRequest req = null;
  151. G8RResponse res = null;
  152. String ending = "***client terminated";
  153. try{
  154. // Decode the G8RRequest from MessageInput
  155. req = (G8RRequest) G8RMessage.decode(mIn);
  156. // Generate a response from G8RRequest
  157. res = genG8RResponse(req);
  158. // Send the response to output
  159. res.encode(mOut);
  160. // Log the information
  161. ending = "[Recieved: " + req + "|Sent: " + res + "]";
  162. }
  163. catch(IOException ex) {
  164. System.err.println("IO in g8rserver");
  165. logger.log(Level.WARNING, "ERROR: IOException found", ex);
  166. }
  167. catch(ValidationException ex) {
  168. System.err.println("VE in g8rserver");
  169. logger.log(Level.WARNING,
  170. "ERROR: ValidationException on input", ex);
  171. }
  172. finally {
  173. try {
  174. clientSocket.close();
  175. }
  176. catch(IOException ex) {
  177. }
  178. }
  179. // Create the log
  180. logger.info(
  181. // Client Address
  182. clientSocket.getRemoteSocketAddress() + ":" +
  183. // Port
  184. clientSocket.getPort() + "-" +
  185. // Thread ID
  186. Thread.currentThread().getId() + " " +
  187. // Append the G8RRequest and Server or ending
  188. ending
  189. );
  190. }
  191.  
  192. /**
  193. * genG8RResponse
  194. * Generate a G8RResponse given a G8RRequest
  195. * @param req The given G8RRequest sent by client
  196. * @return A G8RResponse to send back to the client
  197. * @throws ValidationException if issue on the request sent
  198. */
  199. private static G8RResponse genG8RResponse(G8RRequest req)
  200. throws ValidationException {
  201. G8RResponse res = null;
  202. // A cookie list for the return
  203. CookieList reqCookieList = new CookieList(req.getCookieList());
  204. // Response determination
  205. switch(req.getFunction()) {
  206. case "Poll":
  207. res = pollResponse(req);
  208. N4MServer.applicationHandler("Poll");
  209. break;
  210. case "NameStep":
  211. res = namestepResponse(req);
  212. N4MServer.applicationHandler("NameStep");
  213. break;
  214. case "FoodStep":
  215. res = foodstepResponse(req);
  216. N4MServer.applicationHandler("FoodStep");
  217. break;
  218. // Throw a validation exception
  219. default:
  220. System.err.println("VE 228 in g8rserver");
  221. throw new ValidationException(
  222. "ERROR: Cannot determine function",
  223. req.getFunction());
  224. }
  225. return res;
  226. }
  227.  
  228. /**
  229. * pollResponse
  230. * Creates a response from poll function
  231. * @param req G8RRequest sent from input
  232. * @return G8RResponse for poll
  233. * @throws ValidationException if issue in formatting of G8RResponse
  234. */
  235. private static G8RResponse pollResponse(G8RRequest req)
  236. throws ValidationException {
  237. return new G8RResponse(
  238. "OK",
  239. "NameStep",
  240. "Name (First Last)>",
  241. req.getCookieList()
  242. );
  243. }
  244.  
  245. /**
  246. * namestepResponse
  247. * Creates a response from NameStep function
  248. * @param req G8RRequest sent from input
  249. * @return G8RResponse for NameStep
  250. * @throws ValidationException if issue in formatting of G8RResponse
  251. */
  252. private static G8RResponse namestepResponse(G8RRequest req)
  253. throws ValidationException {
  254. CookieList reqCookieList = req.getCookieList();
  255. if (req.getParams().length != 2) {
  256. throw new ValidationException(
  257. "ERROR: Incorrect number of params",
  258. req.getParams().length + "");
  259. }
  260. // Obtain the first and last names and add to CookieList
  261. reqCookieList.add("FName",req.getParams()[0]);
  262. reqCookieList.add("LName",req.getParams()[1]);
  263. // Generate a response
  264. return new G8RResponse(
  265. "OK",
  266. "FoodStep",
  267. req.getParams()[0] + "'s Food mood>",
  268. reqCookieList
  269. );
  270. }
  271.  
  272. /**
  273. * foodstepResponse
  274. * Creates a response from FoodStep function
  275. * @param req G8RRequest sent from input
  276. * @return G8RResponse for FoodStep
  277. * @throws ValidationException if issue in formatting of G8RResponse
  278. */
  279. private static G8RResponse foodstepResponse(G8RRequest req)
  280. throws ValidationException {
  281. if (req.getParams().length != 1) {
  282. throw new ValidationException(
  283. "ERROR: Incorrect num params",
  284. req.getParams().length + "");
  285. }
  286. String message = "No discount available";
  287. switch(req.getParams()[0]){
  288. case "Mexican":
  289. message = "20% off at Tacopia";
  290. break;
  291. case "Italian":
  292. message = "25% off at Pastastic";
  293. break;
  294. case "American":
  295. message = "Free fries with shake at McDanks";
  296. break;
  297. }
  298. return new G8RResponse(
  299. "OK",
  300. "NULL",
  301. message,
  302. req.getCookieList()
  303. );
  304. }
  305.  
  306.  
  307. }
RAW Paste Data