Guest User

Untitled

a guest
Oct 16th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.12 KB | None | 0 0
  1. import javafx.scene.input.DataFormat;
  2. import java.util.Date;
  3. import java.io.IOException;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. import java.net.ServerSocket;
  7. import java.net.Socket;
  8. import java.text.SimpleDateFormat;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.SimpleTimeZone;
  12.  
  13.  
  14. final class ChatServer {
  15. private static int uniqueId = 0;
  16. // Data structure to hold all of the connected clients
  17. private final List<ClientThread> clients = new ArrayList<>();
  18. private final List<TicTacToeGame> games = new ArrayList<>();
  19. private final int port; // port the server is hosted on
  20.  
  21. /**
  22. * ChatServer constructor
  23. * @param port - the port the server is being hosted on
  24. */
  25. private ChatServer(int port) {
  26. this.port = port;
  27. }
  28.  
  29. /*
  30. * This is what starts the ChatServer.
  31. * Right now it just creates the socketServer and adds a new ClientThread to a list to be handled
  32. */
  33. private void start() {
  34. try {
  35. ServerSocket serverSocket = new ServerSocket(port);
  36. while(true) {
  37. Socket socket = serverSocket.accept();
  38. Runnable r = new ClientThread(socket, uniqueId++);
  39. Thread t = new Thread(r);
  40. clients.add((ClientThread) r);
  41. t.start();
  42. }
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47.  
  48. /**
  49. * Sample code to use as a reference for Tic Tac Toe
  50. *
  51. * directMessage - sends a message to a specific username, if connected
  52. * @param message - the string to be sent
  53. * @param username - the user the message will be sent to
  54. */
  55. private synchronized void directMessage(String message, String username) {
  56. SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
  57. Date now = new Date();
  58. String formattedMessage = format.format(now) + " " + message;
  59. System.out.print(formattedMessage);
  60.  
  61. for (ClientThread clientThread : clients) {
  62. if (clientThread.username.equalsIgnoreCase(username)) {
  63. clientThread.writeMessage(formattedMessage);
  64. }
  65. }
  66. }
  67.  
  68. private synchronized void broadcast(String message){
  69. SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
  70. Date now = new Date();
  71. for(int i=0;i<clients.size();i++){
  72. clients.get(i).writeMessage(format.format(now)+" "+message);
  73. }
  74. }
  75.  
  76. private synchronized void remove(int id){
  77. for(int i=0;i<games.size();i++){
  78. if(games.get(i).getPlayerX().equalsIgnoreCase(clients.get(id).username)||games.get(i).getPlayerO().equalsIgnoreCase(clients.get(id).username)){
  79. games.remove(i);
  80. }
  81. }
  82. clients.remove(id);
  83. }
  84.  
  85. private void close(){
  86. for(int i=0;i<clients.size();i++){
  87. try {
  88. clients.get(i).socket.close();
  89. }catch(IOException e){
  90. e.printStackTrace();
  91. }
  92. remove(i);
  93. }
  94. }
  95.  
  96.  
  97.  
  98. /*
  99. * > java ChatServer
  100. * > java ChatServer portNumber
  101. * If the port number is not specified 1500 is used
  102. */
  103. public static void main(String[] args) {
  104. ChatServer server=null;
  105. if(args.length==0){
  106. server = new ChatServer(1500);
  107. }else{
  108. try {
  109. server = new ChatServer(Integer.parseInt(args[0]));
  110. }catch(NumberFormatException e){
  111.  
  112. }
  113. }
  114. server.start();
  115. }
  116.  
  117.  
  118. /*
  119. * This is a private class inside of the ChatServer
  120. * A new thread will be created to run this every time a new client connects.
  121. */
  122. private final class ClientThread implements Runnable {
  123. Socket socket; // The socket the client is connected to
  124. ObjectInputStream sInput; // Input stream to the server from the client
  125. ObjectOutputStream sOutput; // Output stream to the client from the server
  126. String username; // Username of the connected client
  127. ChatMessage cm; // Helper variable to manage messages
  128. int id;
  129.  
  130. /*
  131. * socket - the socket the client is connected to
  132. * id - id of the connection
  133. */
  134. private ClientThread(Socket socket, int id) {
  135. this.id = id;
  136. this.socket = socket;
  137. try {
  138. sOutput = new ObjectOutputStream(socket.getOutputStream());
  139. sInput = new ObjectInputStream(socket.getInputStream());
  140. username = (String) sInput.readObject();
  141. } catch (IOException | ClassNotFoundException e) {
  142. e.printStackTrace();
  143. }
  144. boolean unique;
  145. boolean noSpace;
  146. do {
  147. unique=true;
  148. noSpace=true;
  149. for (int i = 0; i < clients.size(); i++) {
  150. if (clients.get(i).username.equalsIgnoreCase(username) && clients.get(i).id != id) {
  151. unique=false;
  152. try {
  153. sOutput.writeObject("This username is taken, please choose another");
  154. ChatMessage cm = (ChatMessage) sInput.readObject();
  155. username=cm.getMessage();
  156. } catch (IOException | ClassNotFoundException e) {
  157. e.printStackTrace();
  158. }
  159. }
  160. }
  161. if (username.indexOf(' ')!=-1) {
  162. noSpace=false;
  163. try {
  164. sOutput.writeObject("No spaces allowed in usernames, please pick another");
  165. ChatMessage cm = (ChatMessage) sInput.readObject();
  166. username=cm.getMessage();
  167. } catch (IOException | ClassNotFoundException e) {
  168. e.printStackTrace();
  169. }
  170. }
  171. }while(!unique||!noSpace);
  172. }
  173.  
  174. private boolean writeMessage(String msg){
  175. if(socket.isConnected()){
  176. try {
  177. sOutput.writeObject(msg);
  178. }catch(IOException e){
  179. e.printStackTrace();
  180. }
  181. }
  182. return socket.isConnected();
  183. }
  184.  
  185. /*
  186. * This is what the client thread actually runs.
  187. */
  188. @Override
  189. public void run() {
  190. // Read the username sent to you by client
  191. broadcast(username+" has joined the server!");
  192. while(socket.isConnected()) {
  193. try {
  194. cm = (ChatMessage) sInput.readObject();
  195. } catch (IOException | ClassNotFoundException e) {
  196. e.printStackTrace();
  197. }
  198. if(cm.getRecipient().equalsIgnoreCase(username)){
  199. try{
  200. sOutput.writeObject("You cannot send things to yourself");
  201. continue;
  202. }catch (IOException e){
  203. e.printStackTrace();
  204. }
  205. }
  206. if (cm.getType() == 1) {
  207. try {
  208. sOutput.writeObject("/logout");
  209. sOutput.flush();
  210. remove(clients.indexOf(this));
  211. broadcast(username + " has left the server");
  212. this.socket.close();
  213. break;
  214. } catch (IOException e) {
  215. e.printStackTrace();
  216. }
  217. }else if(cm.getType()==2){
  218. boolean exists=false;
  219. for(int i=0;i<clients.size();i++) {
  220. if(cm.getRecipient().equalsIgnoreCase(clients.get(i).username)){
  221. directMessage(username+"->"+cm.getRecipient()+": "+cm.getMessage(),cm.getRecipient());
  222. directMessage(username+"->"+cm.getRecipient()+": "+cm.getMessage(),username);
  223. exists=true;
  224. break;
  225. }
  226. }
  227. if(!exists) {
  228. try {
  229. sOutput.writeObject("There is no one by that name on this server");
  230. } catch (IOException e) {
  231. e.printStackTrace();
  232. }
  233. }
  234. }else if(cm.getType()==3) {
  235. for(int i=0;i<clients.size();i++){
  236. if(i!=clients.indexOf(this)){
  237. try {
  238. sOutput.writeObject(clients.get(i).username);
  239. }catch(IOException e){
  240. e.printStackTrace();
  241. }
  242. }
  243. }
  244. }else if(cm.getType()==4) {
  245. boolean foundGame=false;
  246. boolean busy=false;
  247. int game=-1;
  248. for(int i=0;i<games.size();i++){
  249. if(games.get(i).getPlayerX().equalsIgnoreCase(this.username)||games.get(i).getPlayerO().equalsIgnoreCase(this.username)){
  250. if(games.get(i).getPlayerX().equalsIgnoreCase(cm.getRecipient())||games.get(i).getPlayerO().equalsIgnoreCase(cm.getRecipient())){
  251. foundGame=true;
  252. game=i;
  253. if(cm.getMessage().equalsIgnoreCase("")){
  254. try{
  255. sOutput.writeObject(games.get(i).toString());
  256. }catch(IOException e){
  257. e.printStackTrace();
  258. }
  259. }else{
  260. int move=-1;
  261. try{
  262. move=Integer.parseInt(cm.getMessage());
  263. }catch(NumberFormatException e){
  264. try {
  265. sOutput.writeObject("Please pass integer moves");
  266. break;
  267. }catch (IOException f){
  268. f.printStackTrace();
  269. }
  270. }
  271. int place = games.get(i).place(move,username);
  272. if(place==-1){
  273. try{
  274. sOutput.writeObject("It is not your turn");
  275. }catch (IOException e){
  276. e.printStackTrace();
  277. }
  278. }else if(place==-2){
  279. try{
  280. sOutput.writeObject("That spot it already taken");
  281. }catch (IOException e){
  282. e.printStackTrace();
  283. }
  284. }else{
  285. directMessage(games.get(i).toString(),username);
  286. directMessage(games.get(i).toString(),cm.getRecipient());
  287. directMessage("Server: "+username+" has taken their turn. It is your turn now",cm.getRecipient());
  288. }
  289. break;
  290. }
  291. }else{
  292. try{
  293. sOutput.writeObject("You are already playing a game");
  294. busy=true;
  295. break;
  296. }catch (IOException e){
  297. e.printStackTrace();
  298. }
  299. }
  300. }else if(games.get(i).getPlayerX().equalsIgnoreCase(cm.getRecipient())||games.get(i).getPlayerO().equalsIgnoreCase(cm.getRecipient())){
  301. try{
  302. sOutput.writeObject("User is already playing a game");
  303. busy=true;
  304. break;
  305. }catch (IOException e){
  306. e.printStackTrace();
  307. }
  308. }
  309. }
  310. if(!foundGame&!busy){
  311. if(cm.getMessage().equalsIgnoreCase("")) {
  312. games.add(new TicTacToeGame(username,cm.getRecipient()));
  313. directMessage("Server: "+username+" has started a game with you",cm.getRecipient());
  314. directMessage(TicTacToeGame.getSampleBox(),cm.getRecipient());
  315. try{
  316. sOutput.writeObject(TicTacToeGame.getSampleBox());
  317. sOutput.writeObject("New game created\nNow place your move");
  318. }catch (IOException e){
  319. e.printStackTrace();
  320. }
  321. }else{
  322. try{
  323. sOutput.writeObject("You currently do not have a game running with this person");
  324. }catch(IOException e){
  325. e.printStackTrace();
  326. }
  327. }
  328. }
  329. if(foundGame){
  330. if(games.get(game).isOver()) {
  331. String opponent="";
  332. int result = games.get(game).checkwinner();
  333. if(games.get(game).getPlayerX().equalsIgnoreCase(username)){
  334. for(int i=0;i<clients.size();i++){
  335. if(clients.get(i).username.equalsIgnoreCase(games.get(game).getPlayerO())){
  336. opponent=clients.get(i).username;
  337. }
  338. }
  339. }else if(games.get(game).getPlayerO().equalsIgnoreCase(username)){
  340. for(int i=0;i<clients.size();i++){
  341. if(clients.get(i).username.equalsIgnoreCase(games.get(game).getPlayerX())){
  342. opponent=clients.get(i).username;
  343. }
  344. }
  345. }
  346. try{
  347. directMessage(games.get(game).toString(),opponent);
  348. if(result==0) {
  349. sOutput.writeObject("The game was a draw");
  350. directMessage("Server: The game was a draw",opponent);
  351. }else if(result==1){
  352. sOutput.writeObject(games.get(game).getPlayerO()+" won the game");
  353. directMessage("Server: "+games.get(game).getPlayerO()+" won the game",opponent);
  354. }else if(result ==2){
  355. sOutput.writeObject(games.get(game).getPlayerX()+" won the game");
  356. directMessage("Server: "+games.get(game).getPlayerX()+" won the game",opponent);
  357. }
  358. }catch(IOException e){
  359. e.printStackTrace();
  360. }
  361. games.remove(game);
  362. }
  363. }
  364. } else{
  365. broadcast(username+":"+cm.getMessage());
  366. }
  367. // Send message back to the client
  368. }
  369. }
  370. }
  371. }
Add Comment
Please, Sign In to add comment