Advertisement
Nickpips

Untitled

Mar 26th, 2016
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. import java.io.*;
  7. import java.net.*;
  8. import java.util.*;
  9.  
  10. public class TCPServer2 {
  11.  
  12. //input command line could be java TCPServer2 [port [IP]]
  13. public static void main(String argv[]) throws Exception
  14. {
  15. final int NUM_BYTES = 80;
  16. int portNum = 11234; //default server's port number, remember to change yours
  17. String servIP="localhost"; //default server's IP
  18.  
  19. if (argv.length > 0)
  20. try {
  21. portNum = Integer.parseInt(argv[0]);
  22. } catch (NumberFormatException e) {
  23. System.err.println("First argument must be an integer");
  24. System.exit(1);
  25. }
  26.  
  27. if (argv.length > 1)
  28. servIP = argv[1]; //get the IP
  29.  
  30. ServerSocket welcomeSocket = null;
  31.  
  32. //BufferedInputStream inFromClient = null;
  33. String sentence;
  34. byte[] buf = new byte[NUM_BYTES];
  35. try {
  36. welcomeSocket = new ServerSocket(portNum); //bind to the server's port number
  37. System.out.println ("Connection Socket Created");
  38.  
  39. while (true)
  40. {
  41. try (Socket connectionSocket = welcomeSocket.accept(); BufferedInputStream inFromClient = new BufferedInputStream(connectionSocket.getInputStream()); PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(),true)) {
  42.  
  43.  
  44. // wait for client's message
  45. System.out.print("Wait for client's message...");
  46. int nRead = inFromClient.read(buf,0,NUM_BYTES);
  47. if (nRead<=0)
  48. {
  49. inFromClient.close(); //since client has closed socket.
  50. connectionSocket.close();
  51. continue; // serve next one
  52. }
  53.  
  54. System.out.println(nRead);
  55. System.out.write(buf,0,nRead);
  56. System.out.println("");
  57.  
  58. //Set up stream for keyboard entry...
  59. Scanner inFromUser = new Scanner(System.in);
  60. System.out.print("Enter message: ");
  61. sentence = inFromUser.nextLine();
  62.  
  63. outToClient.println(sentence);
  64. outToClient.flush();
  65. }
  66.  
  67. }
  68. }
  69. catch(IOException ioEx)
  70. {
  71. System.out.println("Exception ");
  72. }
  73. finally {
  74. welcomeSocket.close();
  75. }
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement