Advertisement
Guest User

Untitled

a guest
Aug 20th, 2014
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. package package1;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7.  
  8. /**
  9. *
  10. * @author Bob
  11. */
  12. public class Server {
  13.  
  14. public static void main(String[] args) {
  15.  
  16. int port = 7777;
  17.  
  18. try {
  19. System.out.println("Hosting on: " + port);
  20.  
  21. ServerSocket ss = new ServerSocket(port);
  22.  
  23. while (true) {
  24. Socket s = ss.accept();
  25. System.out.println("Connection established, ip: "+s.getInetAddress().toString());
  26. Thread t = new Connection(s, port);
  27. t.start();
  28. }
  29. } catch (IOException e) {
  30.  
  31. }
  32. }
  33.  
  34. public static class Connection extends Thread {
  35.  
  36. Socket s;
  37. int port;
  38.  
  39. public Connection(Socket s, int port) {
  40. this.s = s;
  41. this.port = port;
  42. }
  43.  
  44. @Override
  45. public void run() {
  46. try {
  47. PrintWriter out = new PrintWriter(s.getOutputStream(), true);
  48. out.println("Connected to the Server on port: " + port);
  49. s.close();
  50. } catch (IOException e) {
  51. System.err.println("Network error.");
  52. }
  53. }
  54. }
  55. }
  56.  
  57. package package1;
  58.  
  59. import java.io.IOException;
  60. import java.net.InetAddress;
  61. import java.net.Socket;
  62. import java.net.UnknownHostException;
  63. import java.util.Scanner;
  64.  
  65. /**
  66. *
  67. * @author Bob
  68. */
  69. public class Client {
  70.  
  71. public static void main(String[] args) {
  72. int port = 7777;
  73. Socket s = getSocket(port);
  74.  
  75. try {
  76. Scanner sc = new Scanner(s.getInputStream());
  77. System.out.println(sc.nextLine());
  78. s.close();
  79. } catch (Exception e) {
  80.  
  81. }
  82. }
  83.  
  84. private static Socket getSocket(int port) {
  85. Socket s = null;
  86. try {
  87. InetAddress ip = InetAddress.getByName("localhost");
  88. s = new Socket(ip, port);
  89. } catch (UnknownHostException ex) {
  90. System.err.println("Unknown host.");
  91. } catch (IOException ex) {
  92. System.err.println("Network error.");
  93. }
  94. return s;
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement