Gerard-Meier

Sockets within a Thread.

Apr 20th, 2012
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. package sockets;
  2.  
  3. import java.net.Socket;
  4.  
  5. public class Sockets {
  6.  
  7.     public static void main(String[] args) {
  8.         Sockets bar = new Sockets();
  9.     }
  10.    
  11.     public Sockets() {
  12.        
  13.         // Start a new thread (mind you this is ugly test code, you should
  14.         // create a seperate class that implements the runnable interface.
  15.        
  16.         Thread thread = new Thread(new Runnable() {
  17.             @Override
  18.             public void run() {
  19.                 try {
  20.                     System.out.println("trying to create socket");
  21.                    
  22.                     // Adjust this to connect to your server's IP/port.
  23.                     Socket socket = new Socket("127.0.0.1", 8181);
  24.                    
  25.                    
  26.                     System.out.println("socket created");
  27.                 } catch (Exception ex) {
  28.                     System.out.println(ex);
  29.                 }
  30.             }
  31.         });
  32.        
  33.        
  34.         try {
  35.             // Start the thread, basically this calls the thread's run method
  36.             // asynchronously.
  37.             thread.start();
  38.            
  39.             // This will cause the main thread to wait until the other
  40.             // thread is completed.
  41.             thread.join();
  42.         } catch (Exception ex) {
  43.             System.out.println(ex);
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment