Advertisement
Guest User

Untitled

a guest
Aug 28th, 2015
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. package TCP;
  2.  
  3. import java.io.IOException;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. import java.net.UnknownHostException;
  7. import java.util.Scanner;
  8.  
  9. public class ConsoleChat {
  10.  
  11. private ServerSocket providerSocket;
  12. private Socket connection;
  13. private Socket requestSocket;
  14.  
  15. void run() {
  16. try {
  17. providerSocket = new ServerSocket(6666);
  18. Thread serverWait = new Thread() {
  19. @Override
  20. public void run() {
  21. try {
  22. System.out.println("Venter på forbindelse");
  23. connection = providerSocket.accept();
  24. } catch (IOException e) {
  25. // TODO Auto-generated catch block
  26. e.printStackTrace();
  27. }
  28. }
  29. };
  30. Thread clientWait = new Thread() {
  31. @Override
  32. public void run() {
  33. Scanner in = new Scanner(System.in);
  34. System.out.print("Input server id: ");
  35. String ip = in.nextLine();
  36. System.out.println("Forbinder til " + ip);
  37. try {
  38. requestSocket = new Socket(ip, 6666);
  39. System.out.println("Har lavet request");
  40. } catch (UnknownHostException e) {
  41. // TODO Auto-generated catch block
  42. e.printStackTrace();
  43. } catch (IOException e) {
  44. // TODO Auto-generated catch block
  45. e.printStackTrace();
  46. }
  47. }
  48. };
  49. clientWait.start();
  50. serverWait.start();
  51. while (connection == null && requestSocket == null) {
  52. ;
  53. }
  54. if (connection != null) {
  55. clientWait.interrupt();
  56. System.out.println("Forbindelse fra "
  57. + connection.getInetAddress().getHostAddress());
  58. } else {
  59. serverWait.interrupt();
  60. }
  61.  
  62. } catch (IOException e) {
  63. // TODO Auto-generated catch block
  64. e.printStackTrace();
  65. }
  66. }
  67.  
  68. public static void main(String args[]) {
  69. ConsoleChat klient = new ConsoleChat();
  70. klient.run();
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement